【问题标题】:Unable to change header Content-Type to application/json无法将标头 Content-Type 更改为 application/json
【发布时间】:2012-07-11 08:27:20
【问题描述】:

无法使用 Closure 库将标头 Content-Type 更改为 application/json。这个 xhr.send () 是预检的。我已经在服务器端进行了所需的配置。但不知何故,我无法对 Content-Type 进行更改,它始终保持为空。有什么方法可以强制标题更改此代码?

xhr.headers.set('Content-Type','application/json');

Http-Method: OPTIONS
Content-Type: 
Headers: {Accept=[*/*], Accept-Charset=[ISO-8859-1,utf-8;q=0.7,*;q=0.3], accept-encoding=[gzip,deflate,sdch], Accept-Language=[en-US,en;q=0.8], Access-Control-Request-Headers=[origin, content-type], Access-Control-Request-Method=[POST], connection=[keep-alive], Content-Type=[null], Host=[localhost:8181], Origin=[http://localhost], Referer=[http://localhost/?], User-Agent=[Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19]}



Response-Code: 200
Content-Type: text/xml
Headers: {Allow=[POST, GET, OPTIONS, HEAD], Date=[Wed, 11 Jul 2012 16:31:04 GMT], Content-Length=[0]}

【问题讨论】:

  • HTTP OPTIONS 请求通常没有内容主体,因此通常不需要内容类型。您是要指定 response 应该采用的格式,还是确实要设置 request 的内容类型?
  • 你不应该 xhr.setRequestHeader("",""); 吗?
  • 感谢您的回复。 @Gareth 我正在尝试设置请求的内容类型。
  • @the_apj 我试过你的方法并得到警告 - 属性 setRequestHeader 从未在 goog.net.XhrIo 上定义。我正在以初始化方式尝试 XHR。

标签: javascript xmlhttprequest cors google-closure


【解决方案1】:

我认为标题应该添加到 opt_headers 映射中的 xhr.send() 函数中:

goog.net.XhrIo.prototype.send = function(url, opt_method, opt_content, opt_headers)

  • @param {string|goog.Uri} url 请求的 Uri。
  • @param {string=} opt_method 发送方法,默认:GET。
  • @param {string|GearsBlob=} opt_content 发布数据。如果底层 HTTP 请求对象是 Gears HTTP 请求,则这可以是 Gears blob。
  • @param {Object|goog.structs.Map=} opt_headers 要添加到请求的标头映射。

所以:

var xhr = new goog.net.XhrIol
var headers = new goog.structs.Map;
headers.set('Content-Type','application/json')
xhr.send(uri, 'OPTIONS', null, headers);

类似的东西对我们很有效......

问候,

雷内

【讨论】:

  • 感谢 Rene 的指点,我可以成功发送 POST 请求。那是因为Server / Client网络不一致。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2018-07-17
相关资源
最近更新 更多