han*_*ans 5 javascript ajax.request prototypejs cors
我在使用跨源资源共享和原型时遇到了一些麻烦.我对外部资源有简单的发布请求,对于简单的发布请求,必须满足一些规则:
Content-Type必须是application/x-www-form-urlencoded,multipart/form-data或text/plain,一个简单的请求不会使用http Request设置自定义标头,并且Server必须设置Access- Control-Allow-Origin标头正确.
使用vanilla JavaScript XMLHttpRequest一切正常,但是使用PrototypeJS它将无法工作,因为它接缝Prototype设置了一些自定义标头,我不知道如何防止它.
我通过以下方式在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
}
});
Run Code Online (Sandbox Code Playgroud)
知道如何让Prototype发送这么简单的CORS请求吗?
我有一个简单的JavaScript XMLHttpRequest创建的Headers的转储:
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
Run Code Online (Sandbox Code Playgroud)
和原型请求创建的标题:
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
Run Code Online (Sandbox Code Playgroud)
Prototype使用完全不同的标头集...导致控制台中出现以下错误:
XMLHttpRequest无法加载foreign-host.com/bthesis/returnJSON.php.请求标头字段Access-Control-Allow-Headers不允许使用X-Prototype-Version.拒绝得到不安全的标题"X-JSON"
奇怪的是,Web服务器在两种情况下都返回了所请求的资源(我在Chrome的开发者控制台的"资源"视图中看到它)但是接缝原型无法以某种方式访问它
Dor*_*ian 11
我遇到了同样的问题.@mplungjan共享链接包含答案:
您只需x-json通过使用,让浏览器知道标题是安全的access-control-expose-headers
我在Ruby on Rails控制器中使用这一行
headers['Access-Control-Expose-Headers'] = 'x-json'
Run Code Online (Sandbox Code Playgroud)
(这应该很容易翻译成其他编程语言:))
本页面的更多细节
也许您可以在 Ajax 请求中自己设置原始标头,如下所示
new Ajax.Request('some.foreign-host.com/res.php', {
method: 'post',
postBody: 'foo=bar',
requestHeaders: {Origin: 'http://www.my.local-host.com'}
contentType: 'application/x-www-form-urlencoded',
onSuccess: function(e){
// some custom code
}
});
Run Code Online (Sandbox Code Playgroud)
但我自己从未尝试过......原型版本会发生什么?是发出请求后没有任何返回,还是响应被丢弃,还是什么?
| 归档时间: |
|
| 查看次数: |
13318 次 |
| 最近记录: |