1
我在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
您能否提供ajax方法生成的http調用數據? OPTIONS和POST請致電。 –
@Pheagey我寫過我的ajax查詢。我不使用OPTIONS方法進行調用。當我的PHP文件返回錯誤400頭,他給了我這個錯誤。我總是用POST方法發送數據到PHP –
'preflight'是OPTIONS請求。在瀏覽器中打開網絡選項卡並運行代碼。您應該看到.ajax方法會在POSTing之前自動發出OPTIONS請求,因爲請求是一個跨源請求(CORS)類型的調用。 –