gpt4 book ai didi

javascript - 尽管启用了 CORS,$http Angular 仍无法工作

转载 作者:行者123 更新时间:2023-12-03 11:19:37 31 4
gpt4 key购买 nike

在深入研究 Angular 之前,我在服务器上进行了一次彻底的测试,以检查我的 CORS 是否已启用。使用此脚本。

    var xhr     = new XMLHttpRequest();
var param = 'name=mrA';
xhr.open('POST','http://api.otamarket.local/api/cors.json',true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
if (this.status == 200 && this.readyState == 4) {
console.log('response: ' + this.responseText);
}
};
xhr.send(param);

如您所见,它工作得很好。

enter image description here

但是当我通过 $http 使用 Angular 时

var http = "//api.otamarket.local/api/cors.json";
return $http.post(http,credentials);

我收到此错误。

enter image description here

这是 header 响应:

Remote Address:127.0.0.1:80
Request URL:http://api.otamarket.local/api/cors.json
Request Method:OPTIONS
Status Code:405 Method Not Allowed

Request Headers view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.otamarket.local
Origin:http://otakuket.local
Referer:http://otakuket.local/
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

Response Headersview source
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Fri, 28 Nov 2014 03:47:31 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11
X-Powered-By:PHP/5.5.11

这是我启用 CORS 的地方

<VirtualHost *:80>
DocumentRoot "C:\Users\aldri_000\SkyDrive\Program Experiment\websites\api.otamarket.local\public"
ServerName api.otamarket.local
Header set Access-Control-Allow-Origin "*"
<Directory "C:\Users\aldri_000\SkyDrive\Program Experiment\websites\api.otamarket.local">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
Require all granted
</Directory>
</VirtualHost>

这是端点:

public function post_cors()
{
$rsp = array();
$rsp['rsp'] = 'CORS Work';
return $this->response($rsp);
}

如您所见,我已在 apache 服务器的虚拟主机中启用了 CORS。它通过 XHR 工作,但我很困惑为什么它在这里不起作用。

谢谢。

最佳答案

我明白了,使用 $http 调用时内容类型未正确设置。尝试将 headers 属性添加到您的 $http 调用中,如下所示,

$http({
method: 'POST',
url: url,
data: $.param({fkey: "key"}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}

})

关于javascript - 尽管启用了 CORS,$http Angular 仍无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27181630/

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