使用Node.js集成Google静态地图时遇请求被拒问题求助
Let's break down why you're hitting this error and walk through the fixes step by step:
Common Root Cause: Double-Escaped Ampersands
Looking at your code, you're using & to separate parameters in the map URL. In Pug (the template syntax you're working with), manually writing & causes double-escaping—Pug will escape the & again, turning it into & in the final HTML. When the browser sends the request, this becomes & in the actual URL, so the Google API sees parameters like amp;zoom and amp;size instead of zoom and size. That's why it thinks the size parameter is missing.
Fix 1: Use Plain & in the URL
Replace all instances of & with & in your src attribute. Pug will automatically escape these to & in the HTML (which is valid for proper HTML syntax), and the browser will send correct & separators in the request URL.
Here's the corrected code:
.panel.panel-primary .panel-heading h2.panel-title On the map .panel-body img.img-responsive.img-rounded(src="http://maps.googleapis.com/maps/api/staticmap?center=#{location.coords.lat},#{location.coords.lng}&zoom=17&size=400x350&sensor=false&markers=#{location.coords.lat},#{location.coords.lng}&scale=2&key=AIzaSyDt0D6sy4v8BZFVJiAea93aiR63E-GpBL8")
Fix 2: Validate Your Location Variables
If location.coords.lat or location.coords.lng are undefined or null, the center parameter becomes invalid (e.g., undefined,undefined). This can cause the API to misparse the rest of the URL, leading it to miss the size parameter even though it's present.
Add a check in your Node.js route handler to ensure these values exist before rendering the template:
// Example check in your server code if (!location?.coords?.lat || !location?.coords?.lng) { // Handle missing location data (e.g., show an error message) return res.render('your-template', { error: 'Location coordinates are missing' }); } // Proceed to render the template with valid location data
Fix 3: Debug the Rendered URL
To confirm the issue, inspect the image element in your browser's developer tools (right-click → Inspect). Copy the full src URL and paste it into a new tab. This will show you exactly what's being sent to Google, letting you verify if the size parameter is present and correctly formatted.
Bonus Tip
The sensor parameter is deprecated in the Google Static Maps API—you can safely remove it from your URL without any functionality loss.
内容的提问来源于stack exchange,提问作者M. Ma

