如何使用提取与application / json的内容types发布

我有一个响应应用程序,执行一个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); }); } 

但是,由于规范指出application / json是非标准内容types,CORS会阻止它。

但是,我不知道如何修改我的获取调用来执行所需的飞行前请求,让它允许application / json。

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); }); 

在定义您的路由之前。 宣布

 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(); } }); 

在CORS中,请求将在服务器上检查可用的方法。 即在OPTIONS请求中。 当你得到成功的回应,你将能够发送请求。

您也可以为特定页面启用CORS。 在这里学习https://github.com/expressjs/cors