I try to use Fetch()
API to post text/plain
:
fetch('/test', {
method: 'post',
headers: {
'Content-Type': 'text/plain'
},
body: "this is a test"
})
.then(response => response.text())
.then(body => {
console.log(body)
})
This is the router that deal with the request
router.post('/test',(req,res)=>{
console.log(req.body)
res.send('OK')
})
However, the output of console.log(req.body)
is {}
.
I think the problem is the code after body:
I don’t know what is the right way to post text/plain data.
2
Answers
Here, bodyparser.text middleware will only parse the request coming with the type of
text/plain
.Here are a few things you can try to troubleshoot the issue:
Make sure you’re using a middleware like body-parser to parse the request body. Without it, the
req.body
object will be empty.You can try using
FormData
on the client-side to send the data as amultipart/form-data
instead oftext/plain
.If you still want to use text/plain, you can try sending the data as a
stringified JSON object
.Then on the server-side, you can access the data with
req.body.text
.I hope this helps you solve the issue!