与 jQuery ajax post 方法相比,fetch 方法未按预期 posting

fetch method not posting as expected, compared to jQuery ajax post method

我很想使用新的 fetch 方法,我知道它可以用于对 Rest 端点的所有 http 方法调用。

所以我有以下非常简单的 API 端点,我知道它有效,get 和 post 请求有效。我遇到的问题是让 post 请求处理 fetch 方法。

我的获取方法代码是

        var ingredient = {
      'name': 'Salt',
    }; // a JSON object used as the body for the post request

    fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
    {
      method: "POST",
      body: JSON.stringify( ingredient )
    })
    .then(function(res){ console.log( 'Data posted') })

I then get the following error message. 422 (Unprocessable Entity)

如果另一方面我做了一些非常相似的事情,但这次使用经典的 jQuery ajax post 方法它有效。

    $.ajax({
      url: 'http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
      type: 'POST',
      data: 'name=Salt', // or $('#myform').serializeArray()
      success: function() { console.log('Data posted'); }
    });

如有任何帮助,我们将不胜感激,感觉我在这里遗漏了一些小东西,而且网上关于 fetch 方法的文档很少。

这两个请求发送了两个不同的post body,一个是application/x-www-form-urlencoded (jQuery),另一个是application/json.
您必须更改 fetch 调用以发送与 $.ajax 调用相同类型的数据。
您可能必须在获取请求中明确设置内容类型。

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var searchParams = new URLSearchParams();
searchParams.append("name", "Salt");
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
  method: "POST",
  headers: myHeaders,
  body: searchParams
})
.then(function(res){ console.log( 'Data posted') })