我在POST请求时遇到CORS错误, 我的服务器是Nodejs看起来像:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(function(request, response, next) {
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.post('/InsertClient', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
我已尝试设置标头.. 有任何想法吗? 谢谢大家!
答案 0 :(得分:1)
您应该在与OPTIONS
相同的网址上添加POST
路由:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
类似的东西:
app.options('/InsertClient', function(request, response){
response.sendStatus(200);
});
然后,浏览器将首先使用OPTIONS
方法调用url,并检查它是否具有所有相应的cors标记,然后发出实际的POST
请求。