在使用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)載請注明出處。