异步/等待调用不起作用。 我加载了 core-js 和 regenerator-runtime 来解决这个问题,但它仍然无法正常工作。 我猜这是正确组件的问题。 这就是为什么我在下面发布了我的 package.json 和 webpack.config.js 文件。
const getPuzzle = async (wordCount) => {
const response = await fetch(`//puzzle.mead.io/puzzle?wordCount=${wordCount}`, {
mode: 'no-cors'
})
if (response.status === 200) {
const data = await response.json()
return data.puzzle
} else {
throw new Error('Unable to get puzzle')
}
}
错误
Uncaught runtime errors:
ERROR
Unable to get puzzle
at _callee$ (http://localhost:8080/scripts/bundle.js:392:17)
at tryCatch (http://localhost:8080/scripts/bundle.js:367:1062)
at Generator.<anonymous> (http://localhost:8080/scripts/bundle.js:367:3008)
at Generator.next (http://localhost:8080/scripts/bundle.js:367:1699)
at asyncGeneratorStep (http://localhost:8080/scripts/bundle.js:368:70)
at _next (http://localhost:8080/scripts/bundle.js:369:163)
package.json:
{
"name": "boilerplate2",
"version": "1.0.0",
"description": "",
"main": "input.js",
"scripts": {
"dev-server": "webpack serve --open --mode development",
"build": "webpack --mode production",
"start": "webpack serve --open --mode development"
},
"author": "",
"license": "ISC",
"dependencies": {
"@babel/cli": "^7.25.6",
"@babel/preset-env": "^7.25.4",
"babel-loader": "^9.2.1",
"core-js": "^3.38.1",
"live-server": "^1.2.0",
"regenerator-runtime": "^0.14.1",
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.1.0"
}
}
webpack.config.js:
const path = require('path')
module.exports = {
entry: ['core-js/stable', 'regenerator-runtime/runtime', './src/index.js'],
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}]
},
devServer: {
static: {
directory: path.resolve(__dirname, 'public')
},
port: 8080,
devMiddleware: {
publicPath: "//localhost:8080/scripts/"
}
},
devtool: 'source-map'
}
如有任何帮助,我们将不胜感激!
问题不在于 Webpack 或我选择的组件。 问题出在异步请求中的 JavaScript 上:
const getPuzzle = async (wordCount) => {
const response = await fetch(`//puzzle.mead.io/puzzle?wordCount=${wordCount}`, {
mode: 'no-cors'
})
模式:“no-cors”不应该存在。 另外,“https:”应该位于 URL 调用中 //puzzle... 的前面。 一旦解决了这两个问题,一切都很好。