与jQuery ajax post方法相比,fetch方法没有按预期发布
I am eager to use the new fetch method and I understand it can be used for all http method calls to a Rest endpoint.
我很想使用新的fetch方法,我知道它可以用于对Rest端点的所有http方法调用。
So I have the following very simple API endpoint which I know works, get and post requests work. The issue I am having is getting the post request to work on the fetch method.
所以我有以下非常简单的API端点,我知道它可以工作,获取和发布请求工作。我遇到的问题是获取post请求以处理fetch方法。
My code for the fetch method is
我的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)
然后,我收到以下错误消息。 422(不可处理的实体)
If on the other hand I do something very similar but this time using the classic jQuery ajax post method it works.
另一方面,如果我做一些非常相似的事情,但这次使用经典的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'); }
});
Any help here would be appreciated, it feels like I am missing something small here, and documentation on fetch method is scant on the web.
这里的任何帮助将不胜感激,感觉我在这里缺少一些小东西,并且关于fetch方法的文档在网上很少。
1 个解决方案
#1
2
The two request sends two different post bodies one is application/x-www-form-urlencoded
(jQuery) and the other is application/json
.
You'll have to change the fetch call to send the same type of data as the $.ajax call.
You may have to explicitly set the content type in the fetch request.
这两个请求发送两个不同的帖子组,一个是application / x-www-form-urlencoded(jQuery),另一个是application / json。您必须更改提取调用以发送与$ .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') })
更多相关文章
- 在ExtJS中调用超类方法的更好方法
- contains和compareDocumentPosition 方法来确定是否HTML节点间的
- 控制台在node . js中没有“debug”方法吗?
- 利用javascript动态加载头部出现点击事件与hover事件无效解决方
- 类似jQuery的extend扩展方法的实现
- 如何在onchange()事件后调用的方法中将焦点设置为输入字段?
- jsPDF中使用.text()方法的字母间距
- 禁用Chrome严格的MIME类型检查
- javascript 截取字符串方法汇总