[英]AngularJS can't send post request with Content-Type:application/json
[英]jQuery doesn't send post request with content type application/json
我正在使用jQuery 1.10.1 。 我想發送內容類型設置為application / json的POST請求。 我正在執行以下操作:
$.ajax({
type: "post",
url: urlBase + "user/search",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(filter),
success: renderResponse,
error: function(error) {
console.log(error)
}
})
但是未發送POST,並且在錯誤回調中收到以下響應:
對象{readyState = 0,status = 0,statusText =“ error”}
生成了OPTIONS請求,但是沒有后續的POST。 以下是OPTIONS的請求和響應:
Antwort-Header
Access-Control-Allow-Head... X-Requested-With
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Allow-Orig... *
Access-Control-Max-Age 86400
Allow GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Content-Length 0
Server Jetty(6.1.1)
Anfrage-Header
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Access-Control-Request-He... content-type
Access-Control-Request-Me... POST
Cache-Control no-cache
Connection keep-alive
Host localhost:8080
Origin http://localhost
Pragma no-cache
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
這里有什么問題? 如何使jQuery設置所需的內容類型標頭?
訪問控制起源的東西。
瀏覽器不允許在JavaScript中設置Content-Type
標頭。 解決方案是修改響應頭(Java中的示例):
HttpServletResponse hresp = (HttpServletResponse) resp;
hresp.addHeader("Access-Control-Allow-Origin", "*");
hresp.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
它不是特定於jquery的,但它也適用於每個AJAX請求(Dojo或純JavaScript)。
試試這個
var postData = JSON.stringify({"key": value});//this will be your json content
$.ajax({
type: "post",
url: urlBase + "user/search",
contentType: "application/json; charset=utf-8",
data: postData,
dataType: "json,"
success: renderResponse,
error: function(error) {
console.log(error)
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.