首頁  >  問答  >  主體

$.ajax 跨域 options

遇到一个很怪异的问题, 跨域请求的时候, 使用 jquery的ajax()方法发送 post, 会在 post 请求前发送一个 OPTIONS请求, 但是通过 直接通过 post() 方法请求就不会发送 OPTIONS 请求?有什么办法可以在 ajax 跨域请求时, 前端不发送 OPTIONS请求, 或者不处理 OPTIONS 请求吗?

附录:

其中 ajax() 方法设置了这几个参数:

        dataType: "json",
        async: true,
        data: {},
        type: "POST",
        cache: false,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        timeout: 20000,

而 post() 方法什么参数也没设置.


高洛峰高洛峰2864 天前1638

全部回覆(3)我來回復

  • 三叔

    三叔2016-11-17 16:17:51

    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

    这是 jQuery 的 $.ajax() 文件中的,你看对你有没得帮助。

    另外,jQuery 的 $.post 定义如下

    jQuery.post( url [, data ] [, success ] [, dataType ] )

    jQuery.post( [settings ] )

    你把 dataType 设置成 JSON(如果你的服务端返回是 JSON 的话),或者在 settings 里把 dataType 设置为 JSON,再看看效果呢。


    回覆
    0
  • 三叔

    三叔2016-11-17 16:17:30

    跨域是浏览器独有的一种机制,OPTIONS 请求是浏览器在遇到跨域请求的情况下发起的一次类似授权的请求,用于确定服务器端是否允许此次跨域行为。非前端代码控制。

    回覆
    0
  • 欧阳克

    欧阳克2016-11-17 16:17:15

    为什么你使用$.ajax和$.post不一样,可以检查你的代码或者看请求头协议是不是有差别,$.ajax有一个setting。

    查看了一下jquery的文档,发现了一个可能导致你这个问题的原因。还是可以参考MDN上讲解的预请求,非默认允许的情况下是会产生一次预请求的,要和服务端有默契才行。

    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.

    希望以上回答可以帮你找到问题并且解决问题。

    更新:

    按照你给的参数设置不会发起OPTIONS预请求的,只是因为withCredentials: true需要服务端需要设置一个Access-Control-Allow-Credentials: true


    回覆
    0
  • 取消回覆