【发布时间】:2016-08-01 16:53:43
【问题描述】:
我正在尝试在我的 JavaScript 代码中打开一个(跨域)uri。如果我将它复制到我的浏览器并直接打开它,我就可以打开它。但是,如果我在我的 JavaScript 代码中打开它,我会收到 403 Forbidden 错误。这是我的代码:
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.withCredentias = true;
xhr.open('get', uri, 'true');
xhr.onload = function() {
console.log(xhr.response);
}
xhr.send();
这似乎不是 CORS 错误,因为在响应标头中,我可以在 Access-Control-Allow-Origin 部分看到我的源主机。我也没有收到任何 CORS 错误。
有人知道为什么会这样吗?非常感谢您的帮助!
谢谢!
====更新====
直接从浏览器(Chrome)
Request:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:host.com
Pragma:no-cache
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Response:
Cache-Control:max-age=60
Connection:Keep-Alive
Content-Encoding:gzip
Content-Type:application/json; charset=utf-8
Date:Mon, 01 Aug 2016 17:58:20 GMT
Expires:Mon, 01 Aug 2016 17:59:20 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6
Transfer-Encoding:chunked
Vary:Accept-Encoding
来自代码
Request:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:host.com
Origin:myhost.com
Pragma:no-cache
Referer:myhost.com/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, HEAD, OPTIONS
Access-Control-Allow-Origin:myhost.com
Cache-Control:max-age=60
Connection:Keep-Alive
Content-Length:0
Content-Type:application/json; charset=utf-8
Date:Mon, 01 Aug 2016 18:20:54 GMT
Expires:Mon, 01 Aug 2016 18:21:54 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6
【问题讨论】:
-
您可以在手动调用 url 和使用 ajax 请求时添加请求/响应标头吗?另外,
xhr.withCredentias你的问题是错字吗?应该是xhr.withCredentials。 -
是的 withCredentials 是一个错字,在我的代码中是正确的。
-
我稍后会粘贴标题。谢谢
-
曾经解决过这个问题吗?我在使用 electronjs 时遇到了同样的问题......当我从浏览器提交 GET 请求时工作正常,但从 Javascript 完成时给我 403 错误。
标签: javascript html web xmlhttprequest http-status-code-403