跨域Ajax之ContentType:application/json

在使用Ajax跨域請求時,如果設(shè)置Header的ContentType為application/json,會分兩次發(fā)送請求。第
一次先發(fā)送Method為OPTIONS的請求到服務(wù)器,這個請求會詢問服務(wù)器支持哪些請求方法(GET,POST等),
支持哪些請求頭等等服務(wù)器的支持情況。等到這個請求返回后,如果原來我們準(zhǔn)備發(fā)送的請求符合服務(wù)器的規(guī)
則,那么才會繼續(xù)發(fā)送第二個請求,否則會在Console中報錯。

為什么在跨域的時候設(shè)置ContentType為application/json時會請求兩次?其實JQuery的文檔對此有做
說明。

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: Boolean or String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

注意Note后面的描述,在跨域的時候,除了contentType為application/x-www-form-urlencoded, multipart/form-data或者text/plain外,都會觸發(fā)瀏覽器先發(fā)送方法為OPTIONS的請求。

比如說,你原來的請求是方法方法POST,如果第一個請求返回的結(jié)果Header中的Allow屬性并沒有POST方法,
那么第二個請求是不會發(fā)送的,此時瀏覽器控制臺會報錯,告訴你POST方法并不被服務(wù)器支持。

下面看下OPTIONS請求的返回圖

圖中箭頭指向的Allow就是服務(wù)器返回的支持的方法。

不僅如此,如果想要用ContentType:application/json發(fā)送跨域請求,服務(wù)器端還必須設(shè)置一個名為
Access-Control-Allow-Headers 的Header,將它的值設(shè)置為 Content-Type,表明服務(wù)器能夠接收
到前端發(fā)送的請求中的ContentType屬性并使用它的值。否則第二次請求也是發(fā)不出去的,瀏覽器console會
報錯,并提示你服務(wù)器沒有設(shè)置Access-Control-Allow-Headers。

原文出處:http://www.foreverpx.cn
轉(zhuǎn)載請注明出處。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容