是否可以使一个跨域POST ajax请求应用程序/ json? [英] Is is possible to make a cross domain POST ajax request of application/json?

查看:148
本文介绍了是否可以使一个跨域POST ajax请求应用程序/ json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一些csrf的东西,我想知道是否可以通过 Content-Type:application / json

I am testing some csrf stuff, and I am wondering if it is possible to POST a cross domain ajax request with Content-Type: application/json

每次我尝试使用jQuery:

Every time I try to do this with jQuery:

  $.ajax({
    type: "post",
    url: "http://someotherdomain.com/endpoint",
    contentType: "application/json; charset=UTF-8",
    data: {"a": "1"},
    dataType: "json",
    crossDomain: true,
    success: function(data){ alert(data); }, 
    failure: function(data){ alert(data); }
  });

我总是发送 HTTP OPTIONS 请求,而不是 HTTP POSTs

I always send HTTP OPTIONS requests instead of HTTP POSTs.

请注意,我不在乎接收数据,单向邮政是我需要的。

Note- that I don't care about receiving data back, a one way post is all I need.

请注意,内容类型不能是 x-www-form-urlencoded 也可以是GET请求。

Note- that the content-type can't be x-www-form-urlencoded and it can't be a GET request either.

推荐答案

Content-Type:application / json 简单头,因此首先在实际请求之前需要预检请求。您看到的HTTP OPTIONS请求是预检请求。根据CORS规范(http://www.w3.org/TR/cors/):

The Content-Type: application/json header is not a simple header, and therefore first requires a preflight request before the actual request. The HTTP OPTIONS request you are seeing is the preflight request. From the CORS spec (http://www.w3.org/TR/cors/):


标题被认为是如果头字段名为
ASCII字符串,则对于Accept,Accept-Language或
Content-Language不区分大小写的匹配,或者如果它对于
是ASCII不区分大小写的匹配内容-Type和头字段值媒体类型(不包括
参数)是对
应用程序/ x-www-form-urlencoded,multipart / form-data或text / plain的ASCII不区分大小写匹配。

A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept, Accept-Language, or Content-Language, or if it is an ASCII case-insensitive match for Content-Type and the header field value media type (excluding parameters) is an ASCII case-insensitive match for application/x-www-form-urlencoded, multipart/form-data, or text/plain.

为了超过预检请求,服务器需要使用以下标头响应OPTIONS请求:

In order to get past the preflight request, the server needs to respond to the OPTIONS request with the following headers:

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

一旦浏览器收到此响应将会产生实际的HTTP POST请求。请注意,如果您的请求包含其他自定义标头,您需要将它们包含在Access-Control-Allow-Headers响应标头中。您可以在此处了解有关CORS预检请求的详情:

Once the browser receives this response, it will make the actual HTTP POST request. Note that if your request contains additional custom headers, you will need to include them in the Access-Control-Allow-Headers response header. You can learn more about CORS preflight requests here:

http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

这篇关于是否可以使一个跨域POST ajax请求应用程序/ json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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