预检的响应包含无效的HTTP状态代码

时间:2017-03-09 14:36:49

标签: php angularjs http

我对下面的结构有些麻烦。我有2个域:example.comapi.example.com。我在Angular的example.com上写了主站点。我在example.com/app.js中使用此代码来调用api.example.com中的函数:

$http({
    method: 'POST',
    url: 'http://api.example.com/register',
    dataType: 'json',
    crossDomain: true,
    data: {
        email: register.data.email,
        password: register.data.password
    },
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    }
}).then(function(data) {
    console.log(data);
    }, function(data) {
        console.log(data);
});

所有这些都给了我错误

OPTIONS http://api.example.com/register 400 (Bad Request)

XMLHttpRequest cannot load http://api.example.com/register. Response for preflight has invalid HTTP status code 400

我的php代码返回

//some logic code here
if ( $json['status'] == 0 )
{
    header('Access-Control-Allow-Origin: *');  
    header('Access-Control-Allow-Methods: POST, GET'); 
    header('Access-Control-Allow-Headers: Content-Type');  
    header('Content-type: application/json; charset=utf-8');
    echo json_encode($json['data']);
}
else
{
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('HTTP/1.1 400 Bad Request');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Type: application/json; charset=UTF-8');
    http_response_code(400);
}

我的$json['status']=0一切正常。它工作,返回状态200 OK。当我提供错误的参数时,我有$json['status']=1,我得到了一个我所描述的错误。

网络返回的完整标题

Request URL:http://api.example.com/user/register
Request Method:OPTIONS
Status Code:400 Bad Request
Remote Address:78.46.140.200:80
Response Headers
view source
Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Thu, 09 Mar 2017 17:12:22 GMT
Server:Apache
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,az;q=0.2
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.example.com
Origin:http://example.com
Referer:http://example.com/register
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

1 个答案:

答案 0 :(得分:0)

事实上,所有问题都在Angular中。首先是Angular发送OPTIONS请求,只有这个请求有200 OK头发送选择的请求(在我的情况下是POST)。我刚为所有OPTIONS方法制作了200 OK标题。