需要发送带有
POST
的 JSON body
请求。我必须使用fetch
。
原始代码片段,有效:
headers = {'Content-Type': 'application/json'};
body = {path: 'path1'};
fetch(url, {
method: 'post',
headers: headers,
body: JSON.stringify(body)
})
.then(response => {//do work});
现在我必须为
Http-Only cookies
添加 A&A
。
这个链接有答案。基本上,必须添加另一个参数。
后来更新代码为:
fetch(url, {
credentials: 'include',
method: 'post',
headers: headers,
body: JSON.stringify(body)
})
.then(response => {//do work});
服务器在
cookie
中看不到 header
。
然后通过删除其他所有内容来测试
fetch
:
fetch(url, {
credentials: 'include',
method: 'post',
})
.then(response => {//do work});
A&A
部分有效,即服务器现在可以在 cookie
中看到 header
。所以,把身体加回去,不相信它会起作用:
body = {path: 'path1'};
fetch(url, {
credentials: 'include',
method: 'post',
body: JSON.stringify(body)
})
.then(response => {//do work});
果然,没有成功。具有
Express
的 CookieParser
服务器显示主体为 {}
。
添加
Content-Type
标题后:
body = {path: 'path1'};
fetch(url, {
credentials: 'include',
method: 'post',
headers: {'Content-Type': 'application/json'}
body: JSON.stringify(body)
})
.then(response => {//do work});
现在,
cookie
又消失了。猜测是因为添加了新的标头,并替换了fetch
生成的标头,其中包括cookie
。我错了吗?
在搜索时,我发现了一个类似的问题,但没有答案。
我该如何进行?
您可以使用此代码发送 json 正文
var postData = {name: 'ram',class: 'five',};
var url = 'https://example.com/api';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});