Need to send a POST
request with a JSON body
. I have to use fetch
.
Original code snippet, which worked:
headers = {'Content-Type': 'application/json'};
body = {path: 'path1'};
fetch(url, {
method: 'post',
headers: headers,
body: JSON.stringify(body)
})
.then(response => {//do work});
Now I have to add Http-Only cookies
for A&A
.
This link has answer for that. Basically, have to add another parameter.
Afterwards updated code to:
fetch(url, {
credentials: 'include',
method: 'post',
headers: headers,
body: JSON.stringify(body)
})
.then(response => {//do work});
Server doesn't see cookie
in header
.
Then tested the fetch
by removing everything else:
fetch(url, {
credentials: 'include',
method: 'post',
})
.then(response => {//do work});
A&A
part works i.e. Server now sees cookie
in header
. So, added the body back and didn't believe it would work:
body = {path: 'path1'};
fetch(url, {
credentials: 'include',
method: 'post',
body: JSON.stringify(body)
})
.then(response => {//do work});
As expected, it didn't work. The Express
server with CookieParser
is showing that body is {}
.
After added the Content-Type
header:
body = {path: 'path1'};
fetch(url, {
credentials: 'include',
method: 'post',
headers: {'Content-Type': 'application/json'}
body: JSON.stringify(body)
})
.then(response => {//do work});
Now, the cookie
has disappeared again. Guessing it's because of adding a new header, and replacing header generated by fetch
, which includes cookie
. Am I wrong?
While I was searching I found a similar question with no answer.
How should I proceed?