2015-06-29 40 views
0

我得到一个错误CORS而POST请求, 我的服务器的NodeJS的样子:访问控制允许来源的POST请求 - 节点

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

您可能想要使用这个小模块:https://www.npmjs.com/package/cors –

回答

1

你应该在同一URL添加OPTIONS路线为POSThttps://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

喜欢的东西:

app.options('/InsertClient', function(request, response){ 
    response.sendStatus(200); 
}); 

浏览器会那么首先调用URL与OPTIONS方法,并检查是否有所有相应的Cors标志,然后进行实际的POST请求。

相关问题