我对 Web 开发相当陌生,我正在尝试将一些 JSON 数据发送到运行 Express 的 Node.js 服务器,但收到此错误:
Failed to load http://localhost:8888/: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
我不知道这意味着什么。这是客户端获取:
fetch('http://localhost:8888/', {
method: 'PUT',
body: JSON.stringify(this.exercises),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(err => console.error('Error: ' + err))
.then(res => console.log('Success: ' + res));
这是服务器端代码:
app.put('/', (req, res, next) => {
console.log('PUT request received');
console.log(req.body);
});
服务器似乎没有收到请求。我该如何进行这项工作?提前致谢。
最佳答案
确保使用 bodyParser (要访问数据,我们必须使用 body-parser,它允许 Express 读取正文)。 npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
设置cors
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
确保在定义路由之前定义配置。 有关cors的信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
关于javascript - 无法从 fetch PUT 访问 Express 服务器的正文数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51231946/