I cannot send data of <textarea>
to node js, Node js don't see the my sent data.
For Fetch data to Node Js
continueBtn.addEventListener("click", async () => {
console.log(myMsg.value)
console.log(typeof(myMsg.value))
const req = await fetch("/sendmsg", {method: "POST",body: myMsg.value}) ;
console.log("Fetched")
})
For get data in Node js
const {userMessage} = Object.keys(req.body)
CodePudding user response:
You are passing a string to body
. Since you aren't overriding it, it will be given a text/plain
content-type.
On the server you expect req.body
to contain an object.
You haven't shown us what, if any, body parsing middlewares you have configured in your server side code, but none of the common ones will convert something that is text/plain
into an object.
You should:
- Make sure that you have a body parsing middleware configured
- Encode the data you are passing to
body
(e.g. with URLSearchParams) so it has name=value pairs instead of being a plain string.
If you end up passing a string (e.g. if you pass a string of JSON instead of a URLSearchParams object) then you'll also need to set a Content-Type
request header that matches your data format.
CodePudding user response:
"const {userMessage} = Object.keys(req.body)
"
I don't see why you'd be expecting to have a userMessage
key in your body object with the code you pasted. It's possible the data is being passed properly, but you are trying to access the wrong key. I would try logging in your server code to debug the response format as a first step:
console.log(JSON.stringify(req.body))
Let me know if that gets you enough help to move forward, and I can circle back here if not.