调用天气API时遇Uncaught SyntaxError:await仅在async函数等场景有效
解决await只能在async函数或模块顶级作用域使用的错误
你遇到的错误是因为await关键字只能在async函数内部或者ES模块的顶级作用域中使用,你的代码目前是在普通的非模块顶级作用域里直接用了await,所以触发语法错误。下面给两种可行的修复方案:
方案1:将代码包裹在async函数中
这是兼容性最好的方案,适用于大多数场景:
const url = 'https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=Seattle'; const options = { method: 'GET', headers: { 'X-RapidAPI-Key': '2048170619msh07914b56695e5eap11cf22jsneef2a005b0b9', 'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com' } }; // 定义async函数并调用 async function fetchWeather() { try { const response = await fetch(url, options); const result = await response.text(); console.log(result); } catch (error) { console.error(error); } } fetchWeather();
方案2:将脚本标记为ES模块
如果你是在浏览器环境中,可以给引入脚本的<script>标签加上type="module"属性,这样就能直接在顶级作用域使用await:
<script type="module"> const url = 'https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=Seattle'; const options = { method: 'GET', headers: { 'X-RapidAPI-Key': '2048170619msh07914b56695e5eap11cf22jsneef2a005b0b9', 'X-RapidAPI-Host': 'weather-by-api-ninjas.p.rapidapi.com' } }; try { const response = await fetch(url, options); const result = await response.text(); console.log(result); } catch (error) { console.error(error); } </script>
⚠️ 注意:你的代码里直接暴露了RapidAPI的密钥,这会导致密钥泄露,建议把密钥存到环境变量或者后端服务中,不要在前端代码里明文写出来。
内容的提问来源于stack exchange,提问作者Zoya Fatima
相关产品推荐
相关产品推荐

