Did any President of the U.S. earlier serve as a mayor?

You just made Rudy Giuliani sad, depending on your definition of “directly”.

Calvin Coolidge was mayor of Northampton, MA from 1910-1912.

I’d count Giuliani. The last elective office he held was Mayor of NYC.