预检的响应具有无效的HTTP状态代码
问题描述:
我在folowing结构中遇到了一些麻烦。我有2个域名:example.com
和api.example.com
。我在Angular上写了example.com
的主站点。我用这个代码example.com/app.js
调用函数api.example.com
:预检的响应具有无效的HTTP状态代码
$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);
});
而且所有ofthis给我的错误
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
一切都OK。它工作,返回状态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
答
作为一个事实完整标题,所有的问题在角。首先Angular发送OPTIONS请求,只有当这个请求有200 OK头发送选择的请求(在我的情况下POST)。我为所有OPTIONS方法创建了200 OK头。
您能否提供ajax方法生成的http调用数据? OPTIONS和POST请致电。 –
@Pheagey我写过我的ajax查询。我不使用OPTIONS方法进行调用。当我的PHP文件返回错误400头,他给了我这个错误。我总是用POST方法发送数据到PHP –
'preflight'是OPTIONS请求。在浏览器中打开网络选项卡并运行代码。您应该看到.ajax方法会在POSTing之前自动发出OPTIONS请求,因为请求是一个跨源请求(CORS)类型的调用。 –