【发布时间】:2018-07-07 12:16:04
【问题描述】:
从我的 localhost:8080 向外部 API 发起 POST 请求时,我经常遇到 405 问题。我尝试使用许多不同的选项,但我没有得到问题的关键。
URL = api end point; //Your URL
var datajson = '{'
+'"image" : "'+imageBase64+'"'
+'}';
var req = new XMLHttpRequest();
var body = JSON.parse(datajson)
if ('withCredentials' in req) {
req.open('POST', URL, true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = handleResponse(req);
req.send(body);
}
我在浏览器中遇到的错误是:
选项http://blablabla 405(不允许的方法)
sendToBioFace @ myjavascript.js:38
发送@myjavascript.js:56
onclick @(索引):13
(index):1 无法加载http://blablabla: 预检响应具有无效的 HTTP 状态代码 405
在标题下方查找:
Request URL:http://blablabla.com
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address: destinationip:16111
Referrer Policy:no-referrer-when-downgrade
Response Headers
Access-Control-Allow-Headers:X-Requested-With,Content-Type
Access-Control-Allow-Origin:*
Access-Control-Request-Method:POST,GET,PUT,DELETE,OPTIONS
Allow:POST
Content-Length:1569
Content-Type:text/html; charset=UTF-8
Date:Sun, 28 Jan 2018 19:13:42 GMT
Server:Microsoft-HTTPAPI/2.0
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:es-ES,es;q=0.9,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host: destinationip:16111
Origin:http://localhost:8080
Pragma:no-cache
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
【问题讨论】:
-
我在您的请求标头中没有看到“方法”?
-
远程
blablabla端有问题。联系他们的支持团队并检查他们的文档以确保您正确地遵循它。 -
每当您向远程 API 发送 CORS 请求时,浏览器都会发送一个 OPTIONS 请求,该请求必须返回状态 200 和三个标头值
Access-Control-Allow-Headers、Access-Control-Allow-Origin、@987654328 @。然后,浏览器将根据这些值检查您的 CORS 请求,并且仅在值和您的请求匹配时发送它。显然,远程 API 不允许 OPTIONS 请求,因此您不能从您的域调用它们的 JSON 端点。在不知道您使用的是哪个远程 API 的情况下,我们无法为您提供更多建议。 -
从 Postman 或 python 脚本发出请求......它可以工作。
-
@JorgeGarciaDominguez 这是因为 CORS 是为浏览器设计的。邮递员和你的 python 脚本不应该也不应该尊重它。
标签: javascript api cors