[英]How to use fetch to post with content-type of application/json
I have a react application that does a fetch call to an API as follows: 我有一个react应用程序,它对API进行提取调用,如下所示:
postForm(state) {
var formData = state.formData;
return fetch('http://localhost:3000/api/V0.1/formSubmit', {method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(formData)})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
return null;
})
.catch((error) => {
console.error(error);
});
}
however, it gets blocked by CORS as the spec states that application/json is non-standard content type. 但是,由于规范指出application / json是非标准的内容类型,因此它被CORS阻止。
However, I'm not sure how I can modify my fetch call to perform the required pre-flight request to get it to allow application/json. 但是,我不确定如何修改获取请求以执行所需的飞行前请求,以使其允许应用程序/ json。
The API call is: API调用为:
app.post("/api/v0.1/formSubmit", function(req, res) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', '*');
var formData=req.body;
console.log(formData);
res.status(200).json(formData);
});
Before defining your routing. 在定义您的路由之前。 declare
宣布
app.use(function(req, res, next) {
var oneof = false;
if(req.headers.origin) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
oneof = true;
}
if(req.headers['access-control-request-method']) {
res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
oneof = true;
}
if(req.headers['access-control-request-headers']) {
res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
oneof = true;
}
if(oneof) {
res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
}
// intercept OPTIONS method
if (oneof && req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});
In CORS, the request is checked for available methods on server. 在CORS中,将检查请求中服务器上的可用方法。 ie in OPTIONS request.
即在OPTIONS请求中。 When you get the successful response, you will able to send request.
收到成功的响应后,便可以发送请求。
You can enable CORS for specific pages also. 您也可以为特定页面启用CORS。 study here https://github.com/expressjs/cors
在这里学习https://github.com/expressjs/cors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.