我在跨源资源共享和原型(prototype)方面遇到了一些问题。我有一个对国外资源的简单post请求,对于一个简单的post请求,有一些必须满足的规则:
Content-Type必须是application/x-www-form-urlencoded, multipart/form-data, or text/plain, 一个简单的请求不会用http Request设置自定义的headers,Server必须设置Access-Control-Allow-Origin header 正确。
使用 vanilla JavaScript XMLHttpRequest 一切正常,但使用 PrototypeJS 则无法正常工作,因为它接缝 Prototype 设置了一些自定义 header ,我不知道如何防止它。
我通过以下方式在 Prototype 中尝试过:
new Ajax.Request('some.foreign-host.com/res.php', {
method: 'post',
postBody: 'foo=bar',
contentType: 'application/x-www-form-urlencoded',
onSuccess: function(e){
// some custom code
}
});
知道如何让 Prototype 发送这样一个简单的 CORS 请求吗?
我有一个由普通 JavaScript XMLHttpRequest 创建的 header 转储:
POST /bthesis/returnJSON.php HTTP/1.1
Host: foreign-host.com
Connection: keep-alive
Referer: this-host.com
Content-Length: 9
Origin: this-host.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*
User-Agent: [...]
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
以及由原型(prototype)请求创建的 header :
OPTIONS /bthesis/returnJSON.php HTTP/1.1
Host: foreign-host.com
Connection: keep-alive
Referer: this-host.com
Access-Control-Request-Method: POST
Origin: this-host.com
Access-Control-Request-Headers: X-Prototype-Version, X-Requested-With, Content-type, Accept
Accept: */*
User-Agent: [...]
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Prototype 使用完全不同的 header 集...这会导致控制台出现以下错误:
XMLHttpRequest 无法加载 foreign-host.com/bthesis/returnJSON.php。 Access-Control-Allow-Headers 不允许请求 header 字段 X-Prototype-Version。 拒绝获取不安全的 header “X-JSON”
奇怪的是,Web 服务器在这两种情况下都返回了请求的资源(我在 chrome 开发者控制台的“资源” View 中看到了它)但它接缝表明原型(prototype)无法以某种方式访问它
最佳答案
我遇到了同样的问题。 @mplungjan 共享的链接包含答案:
您只需使用 access-control-expose-headers
让浏览器知道 x-json
header 是安全的
我在 Ruby on Rails Controller 中使用这一行
headers['Access-Control-Expose-Headers'] = 'x-json'
(这应该很容易翻译成其他编程语言:))
关于此的更多详细信息 page
关于javascript - 使用 PrototypeJS 进行跨源资源共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413762/