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


CORS AJAX request from a NodeJS server to a PHP server

所以我正在向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

知道我可能错过了什么吗?

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

Access-Control-Allow-Methods: GET, POST

客户端需要知道服务器可以处理哪些方法作为预检请求的一部分