我试图使用fetch POST一个JSON对象。
根据我的理解,我需要将一个字符串化的对象附加到请求的主体,例如:
fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
当使用jsfiddle的JSON回显时,我希望看到我发送的对象({a: 1, b: 2})回来,但这不会发生- chrome devtools甚至不显示JSON作为请求的一部分,这意味着它没有被发送。
从搜索引擎,我结束了这个主题的非json发布数据与fetch,所以我认为我将添加这个。
对于非json,你不必使用表单数据。你可以简单地设置Content-Type头为application/x-www-form-urlencoded,并使用一个字符串:
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: 'foo=bar&blah=1'
});
构建body字符串的另一种方法是使用库,而不是像上面那样将其输入。例如query-string或qs包中的stringify函数。所以使用它看起来像这样:
import queryString from 'query-string'; // import the queryString class
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
});
它可能对某些人有用:
我遇到的问题是,formdata没有为我的请求发送
在我的案例中,是以下标题的组合也导致了这个问题和错误的Content-Type。
我和请求一起发送了这两个头文件当我删除了工作的头文件时它并没有发送formdata。
"X-Prototype-Version": "1.6.1",
"X-Requested-With": "XMLHttpRequest"
另外,其他答案表明,Content-Type头需要正确。
对于我的请求,正确的Content-Type头是:
“内容类型”:“应用程序/ x-www-form-urlencoded;charset = utf - 8”
所以底线是,如果你的formdata没有附加到Request,那么它可能是你的header。试着减少标题,然后一个一个地添加它们,看看你的问题是否得到解决。
我认为,我们不需要将JSON对象解析为字符串,如果远程服务器接受JSON到他们的请求,只需运行:
const request = await fetch ('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { a: 1, b: 2 }
});
比如curl请求
curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'
如果远程服务不接受json文件作为主体,只需发送一个dataForm:
const data = new FormData ();
data.append ('a', 1);
data.append ('b', 2);
const request = await fetch ('/echo/form', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: data
});
比如curl请求
curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'
如果你使用纯json REST API,我已经在fetch()周围创建了一个薄包装器,其中有许多改进:
// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data), // send it as stringified json
credentials: api.credentials, // to keep the session on the request
headers: Object.assign({}, api.headers, headers) // extend the headers
}).then(res => res.ok ? res.json() : Promise.reject(res));
};
// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
'csrf-token': window.csrf || '', // only if globally set, otherwise ignored
'Accept': 'application/json', // receive json
'Content-Type': 'application/json' // send json
};
// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
api[method] = api.bind(null, method);
});
要使用它,你有变量api和4个方法:
api.get('/todo').then(all => { /* ... */ });
在一个async函数中:
const all = await api.get('/todo');
// ...
jQuery示例:
$('.like').on('click', async e => {
const id = 123; // Get it however it is better suited
await api.put(`/like/${id}`, { like: true });
// Whatever:
$(e.target).addClass('active dislike').removeClass('like');
});