从NodeJS服务器到PHP服务器的CORS AJAX请求

时间:2015-06-16 09:30:09

标签: php ajax angularjs node.js cors

所以我正在从节点服务器向PHP服务器发出AJAX请求。 PHP服务器如下所示:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

echo json_encode($data);

请求通过AngularJS列表发送:

app.controller('MainController', function($scope, $http) {

var req = {
    method: 'POST',
    url: 'http://testsite.com/api/login',
    headers: {
        'Content-Type': 'application/json'
    },
    data: { 
        Data : { 
            email: 'test',
        }
    }
}

$http(req)
    .success(function(response){ console.log(response); })
    .error(function(){ console.log("error")});
});

这完美无缺。当我在NodeJS应用程序中运行时,问题就出现了,除了带有ExpressJS的NodeJS正在运行node bin/www之外,一切都完全相同。我得到的错误是:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers
XMLHttpRequest cannot load http://testsite.com/api/login. Request header field Content-Type is not allowed by Access-Control-Allow-Headers

关于我可能遗失的任何想法?

1 个答案:

答案 0 :(得分:0)

尝试在PHP服务器响应中添加此标头

Access-Control-Allow-Methods: GET, POST

客户需要知道服务器可以在飞行前请求中处理哪些方法