Google Apps Script使用UrlFetchApp拼接URL参数时提示无效参数错误
问题原因
- JavaScript 中
${变量名}的插值语法仅在使用**反引号()**(键盘ESC键下方的按键)包裹字符串时才会生效,你当前使用单引号包裹apiURL,变量不会被替换,最终请求的URL会包含字面量${location}`这类无效字符串,触发参数报错 - URL拼接不需要使用HTML转义字符
&,直接使用&拼接参数即可
修复方案
直接修改apiURL的定义行,将包裹符号改为反引号,同时替换转义符即可:
function myFunction() { const key = "606503c07f32a32677df7e0f" const ss= SpreadsheetApp.getActiveSpreadsheet() const wsLocation = ss.getSheetByName("Location") const wsLiveData = ss.getSheetByName("Live Data") const location = wsLocation.getRange("A2").getValue() const units = wsLocation.getRange("B2").getValue() const highCell=wsLiveData.getRange("B4") const lowCell=wsLiveData.getRange("C4") // 仅修改这一行即可 let apiURL= `https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${key}&units=${units}` const resText = UrlFetchApp.fetch(apiURL).getContentText() console.log(resText) }
如果要避免location中存在空格、特殊符号导致请求异常,可以给参数加上编码处理:
let apiURL= `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(location)}&appid=${key}&units=${encodeURIComponent(units)}`
内容的提问来源于stack exchange,提问作者Moses
相关产品推荐
相关产品推荐

