Jquery.post 的获取模拟

Jquery.post's fetch analog

我已尝试从 jQuery.post 转移到名为 fetch 的默认功能来发出请求。我已经意识到,看起来相同的查询具有不同的行为。

jQuery.post:

jQuery.post({
    type: "POST",
    url: '/core/comment/add',
    data: {
        type: "article",
        identity: 1931,
        body: "Some stuff"
    }
}).done(function() {
    console.log(arguments);
}).fail(function() {
    console.log("fail");
});

获取:

fetch('/core/comment/add', {
    method: 'POST',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type':'application/json',
    },
    body: JSON.stringify({
        type: "article",
        identity: 1931,
        body: "Some stuff"
    })
}).then(function(response) {
    console.log(response);
}).catch(function(e) {
    console.log(e);
});

jQuery.post情况下一切正常,但fetchreturns我的状态为404。我也尝试添加credentials: 'same-origin'选项,尝试发送数据 w/o JSON.stringify 和 headers,但没有任何变化 - $_POST 为空。 那么有什么区别以及如何实现相同的行为?

https://pastebin.com/yw9xj5ZD 显示 jQuery.post 已发送 application/x-www-form-urlencoded 数据,因此要使用 Fetch API 执行相同的操作,请使用以下代码:

fetch('/core/comment/add', {
    method: 'POST',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type':'application/x-www-form-urlencoded',
    },
    body: "type=article&identity=1931&body=Some stuff"
    })
}).then(function(response) {
    console.log(response);
}).catch(function(e) {
    console.log(e);
});

即:

  • Content-Type request-header 值更改为 application/x-www-form-urlencoded
  • 使用 body 的字符串,格式为 type=article&identity=1931&body=Some stuff