无法在jQuery.ajax中将content-type设置为'application/json' [英] Cannot set content-type to 'application/json' in jQuery.ajax

查看:497
本文介绍了无法在jQuery.ajax中将content-type设置为'application/json'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有此代码时

$.ajax({
    type: 'POST',
    //contentType: "application/json",
    url: 'http://localhost:16329/Hello',
    data: { name: 'norm' },
    dataType: 'json'
});

在Fiddler中,我可以看到以下原始请求

in Fiddler I can see following raw request

POST http://localhost:16329/Hello HTTP/1.1
Host: localhost:16329
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:14693/WebSite1/index.html
Content-Length: 9
Origin: http://localhost:14693
Pragma: no-cache
Cache-Control: no-cache

name=norm

但是我要尝试的是将内容类型从 application/x-www-form-urlencoded 设置为 application/json .但是这段代码

But what I'm trying is to set content-type from application/x-www-form-urlencoded to application/json. But this code

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: 'http://localhost:16329/Hello',
    data: { name: 'norm' },
    dataType: "json"
});

生成奇怪的请求(我可以在Fiddler中看到)

Generates strange request (which I can see in Fiddler)

OPTIONS http://localhost:16329/Hello HTTP/1.1
Host: localhost:16329
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://localhost:14693
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache

那是为什么?什么时候应该将其张贴在哪里?我的内容类型在哪里设置为application/json?请求参数由于某种原因而消失了.

Why is that? What is OPTIONS when it should be POST there? And where is my content-type set to application/json? And request parameters has gone for some reason.

更新1

在服务器端,我有非常简单的RESTful服务.

On server side I have really simple RESTful service.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestfulService : IRestfulService
{
    [WebInvoke(
        Method = "POST",
        UriTemplate = "Hello",
        ResponseFormat = WebMessageFormat.Json)]
    public string HelloWorld(string name)
    {
        return "hello, " + name;
    }
}

但是由于某种原因,我无法使用参数调用此方法.

But for some reason I can't call this method with parameters.

更新2

很抱歉没有回答这么久.

Sorry for not answering so long.

我已将这些标头添加到服务器响应中

I've added these headers to my server response

 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: Content-Type
 Access-Control-Allow-Methods: POST, GET, OPTIONS

这没有帮助,我收到了服务器的不允许方法错误.

It didn't help, I have Method not allowed error from server.

这是我的提琴手说的

因此,现在我可以确定我的服务器接受 POST,GET,OPTIONS (如果响应标头按我预期的那样工作).但是为什么不允许使用方法"?

So, now I can be sure that my server accepts POST, GET, OPTIONS (if response headers work like I expect). But why "Method not allowed"?

来自服务器的WebView响应(您可以在上面的图片中看到 Raw 响应)看起来像这样

In WebView response from server (you can see Raw response on picture above) looks like this

推荐答案

从url选项中删除http://似乎可以确保发送正确的HTTP POST标头.

It would seem that removing http:// from the url option ensures the the correct HTTP POST header is sent.

我认为您不需要完全限定主机名,只需使用如下相对URL.

I dont think you need to fully qualify the name of the host, just use a relative URL as below.

   $.ajax({
      type: "POST",
      contentType: "application/json",
      url: '/Hello',
      data: { name: 'norm' },
      dataType: "json"
   });

一个有效的例子:

        $.ajax({
            type: "POST",
            url: siteRoot + "api/SpaceGame/AddPlayer",
            async: false,
            data: JSON.stringify({ Name: playersShip.name, Credits: playersShip.credits }),
            contentType: "application/json",
            complete: function (data) {
            console.log(data);
            wait = false;
        }
    });

可能相关: jQuery $ .ajax(),$ .post发送"; OPTIONS"在Firefox中为REQUEST_METHOD

修改: 经过更多研究后,我发现OPTIONS标头用于确定是否允许来自原始域的请求.使用小提琴手,我在服务器的响应头中添加了以下内容.

After some more research I found out the OPTIONS header is used to find out if the request from the originating domain is allowed. Using fiddler, I added the following to the response headers from my server.

 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: Content-Type
 Access-Control-Allow-Methods: POST, GET, OPTIONS

浏览器收到此响应后,便会发送带有json数据的正确POST请求.似乎默认的采用表单加网址编码的内容类型被认为是安全的,因此不会进行额外的跨域检查.

Once the browser received this response it then sent off the correct POST request with json data. It would seem that the default form-urlencoded content type is considered safe and so does not undergo the extra cross domain checks.

您似乎需要将前面提到的标头添加到服务器对OPTIONS请求的响应中.当然,您应该配置它们以允许来自特定域而不是所有域的请求.

It looks like you will need to add the previously mentioned headers to your servers response to the OPTIONS request. You should of course configure them to allow requests from specific domains rather then all.

我使用以下jQuery对此进行了测试.

I used the following jQuery to test this.

$.ajax({
   type: "POST",
   url: "http://myDomain.com/path/AddPlayer",
   data: JSON.stringify({
      Name: "Test",
       Credits: 0
   }),
   //contentType: "application/json",
   dataType: 'json',
   complete: function(data) {
       $("content").html(data);
  }
});​

参考文献:

  • http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  • http://enable-cors.org/
  • https://developer.mozilla.org/en/http_access_control

这篇关于无法在jQuery.ajax中将content-type设置为'application/json'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆