无法从提取PUT到快递服务器访问正文数据 [英] Can't access body data from fetch PUT to express server
问题描述
我对Web开发还很陌生,我正尝试将一些JSON数据发送到运行express的node.js服务器,但出现此错误:
I'm fairly new to web development and I'm trying to send some JSON data to a node.js server running express but I'm getting this error:
无法加载 http://localhost:8888/:方法PUT不允许 飞行前响应中的Access-Control-Allow-Methods.
Failed to load http://localhost:8888/: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
我不知道这意味着什么.这是客户端获取:
I have no idea what this means. This is the client-side fetch:
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);
});
服务器似乎甚至没有收到请求.我该如何工作?预先感谢.
The server doesn't even seem to receive the request. How do I make this work? Thanks in advance.
推荐答案
确保使用bodyParser(要访问数据,我们必须使用body-parser,它允许express读取body). npm install --save body-parser
Make sure to use bodyParser (to get access to the data we have to use body-parser, it allows express to read the body). 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/zh-美国/docs/Web/HTTP/CORS
Make sure that you define the configurations beforedefining routes. Info about cors: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
这篇关于无法从提取PUT到快递服务器访问正文数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!