gpt4 book ai didi

php - 预检响应具有无效的 HTTP 状态代码

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:25:22 25 4
gpt4 key购买 nike

我在使用以下结构时遇到了一些问题。我有 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 并且我得到了一个我描述的错误。

网络返回的完整 header

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 中。首先 Angular 发送 OPTIONS 请求,只有当这个请求有 200 OK header 时才发送选定的请求(在我的例子中是 POST)。我刚刚为所有 OPTIONS 方法制作了 200 OK header 。

关于php - 预检响应具有无效的 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42698083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com