已加载core-js与regenerator-runtime,Webpack下async/await仍无法运行求助
问题解决:async/await调用fetch报错"Unable to get puzzle"
核心原因
你的问题不是async/await的转译问题(Babel+core-js的配置已经生效,错误栈里能看到regenerator-runtime的调用痕迹),而是fetch请求中设置了mode: 'no-cors'导致的:
- 当使用
no-cors模式时,浏览器会强制限制对响应的访问权限,此时response.status会始终返回0(而非实际的HTTP状态码) - 同时你无法调用
response.json()来解析响应内容,这直接触发了你的错误分支
解决方案
方案1:移除mode: 'no-cors'
如果目标服务器(puzzle.mead.io)支持CORS,直接去掉这个配置即可:
const getPuzzle = async (wordCount) => { const response = await fetch(`//puzzle.mead.io/puzzle?wordCount=${wordCount}`) if (response.ok) { // 用response.ok替代status===200,覆盖200-299范围内的成功状态码,更严谨 const data = await response.json() return data.puzzle } else { throw new Error('Unable to get puzzle') } }
方案2:配置webpack代理(如果目标服务器不支持CORS)
如果目标服务器没有配置CORS头,可以通过webpack dev server的代理功能绕过跨域限制:
修改webpack.config.js中的devServer配置:
devServer: { static: { directory: path.resolve(__dirname, 'public') }, port: 8080, devMiddleware: { publicPath: "//localhost:8080/scripts/" }, // 添加代理配置 proxy: { '/puzzle': { target: 'https://puzzle.mead.io', changeOrigin: true } } }
然后修改fetch请求路径:
const response = await fetch(`/puzzle?wordCount=${wordCount}`)
额外说明
你的Babel和webpack配置是正确的:
- entry中已经引入了
core-js/stable和regenerator-runtime/runtime @babel/preset-env已经正确配置,async/await的转译工作正常
内容的提问来源于stack exchange,提问作者Tachyon80
相关产品推荐
相关产品推荐

