在本地的http.request规定了post方法,但在chrome控制台显示的是get方法

最近测试一个小功能的时候,偶然遇到这个问题,在本地使用的jQuery.ajax,并定义了type: "post"

部分代码:

                $.ajax({
                    header: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    type: "post",
                    url: url,
                    async: true,
                    data: {
                        access_token: access_token,
                        id_card_side: "front",
                        image: imageBase
                    },
                    dataType: "jsonp",
                    timeout: 30000,
                    success: function (data) {
                        console.log("解析成功");
                        console.log(data);
                    },
                    error: function (xhr) {
                        console.log("请求解析失败");
                    }
                });

但是在浏览器测试的时候,依然会变成get请求,找了很多帖子,最终找到原因:

*注:首先排除了请求路径错误的问题,如果你也遇到这种情况,先检查请求路径是否正确,结尾是否多/。

我这里出现这种情况的原因是因为定义了dataType: "jsonp",跨域请求,这样的话即使规定了type: "post",jQuery也会帮你变成get请求,具体原理可参考jQuery API中文文档

jQuery API中文文档上指出:在远程请求时(不在同一个域下),所有POST请求都将转为GET请求。因为将使用DOM的script标签来加载。

另外ajax函数写法在从jQuery 1.5.1开始版本之后就出现了新的ajax函数写法,建议使用新写法。

例如:

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
  beforeSend: function ( xhr ) {
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
  }
}).done(function ( data ) {
  if( console && console.log ) {
    console.log("Sample of data:", data.slice(0, 100));
  }
});

jqXHR.done(function(data, textStatus, jqXHR) {});
一个可供选择的 success 回调选项的构造函数,.done()方法取代了的过时的jqXHR.success()方法。

原文地址:https://www.cnblogs.com/zh-1721342390/p/9318211.html