contentType:'application / json'和POST方法(JavaScript) [英] contentType: 'application/json' with POST method (JavaScript)
问题描述
我需要用JavaScript创建一个Web服务器客户端,我在定义Request头时遇到了一些问题。
I need to create a web server client in JavaScript and I have some problems to define Request headers.
我需要POST方法和Content-Type:application / json。
I need POST method and Content-Type: "application/json".
我试过这个:
$.ajax({
url: 'http://MyWebServiceAddress',
data: JSON.stringify({user:'user',pass:'pass'}),
type: 'POST',
crossDomain: true,
dataType: 'json',
success: function () {
alert("success")
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + xhr.status + "\n" +
"Message: " + xhr.statusText + "\n" +
"Response: " + xhr.responseText + "\n" + thrownError);
}
});
但如果我把contentType这样:
But if I put contentType like this:
contentType:'application / json; charset = utf-8',
contentType: 'application/json; charset=utf-8',
然后查看Chrome开发工具的请求我可以看到该方法已更改为OPTIONS并输入text / plain
and look then the request with Chrome Dev Tools I can see that method was changed to "OPTIONS" and type to "text/plain"
任何人都可以帮助我吗?我不必使用Ajax,所以如果有人知道一个好的JavaScript库以使客户端更容易,可能会导致我的问题
Anyone can help me? I don't have to use Ajax, so if someone know a good JavaScript library to make client easier, maybe can result my problems
推荐答案
你需要像你写的一样设置 contentType
标题; contentType
用于请求本身,而 dataType
标头用于您希望从服务器返回的响应。因此,如果您将 contentType
添加到 $。ajax
请求,它看起来是正确的。
You do need to set the contentType
header just as you've written; the contentType
is for the request itself, while the dataType
header is for the response you're expecting back from the server. So if you add that contentType
to the $.ajax
request, it looks correct.
OPTIONS请求是一个不同的问题:因为你必须发出跨域请求而发送,这意味着ajax请求的服务地址( http:/ / MyWebServiceAddress
)与当前页面的origin地址不同。是这样的吗?一个例子是,如果您的页面来自 http://example.com
,并且您正在向 http://twitter.com发出请求
来自该页面。您可以在此处了解有关跨源或CORS请求的更多信息。底线是 $ .ajax
必须在发布JSON数据之前发出单独的ORIGIN请求,然后它会发出POST请求 - 当且仅当服务器 http:// MyWebServiceAddress
配置为允许来自您网页域的CORS请求时。有关更多详细信息,请参阅上面的CORS链接。
The "OPTIONS" request is a different issue: that's being sent because you must be making a "cross-origin" request, meaning the ajax request's service address (http://MyWebServiceAddress
) is different from the current page's "origin" address. Is that the case? An example would be if your page comes from http://example.com
, and you are making a request to http://twitter.com
from that page. You can read more about cross-origin, or CORS, requests here. The bottom line is that $.ajax
has to make a separate ORIGIN request before posting JSON data like you're doing, and then it will make the POST request -- if and only if the server at http://MyWebServiceAddress
is configured to allow CORS requests from your page's domain. See that CORS link above for more details.
这篇关于contentType:'application / json'和POST方法(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!