I have a client-side script running to send the string "Y" to the server. I set up a console.log on the client-side (which you can see below) and another on the server-side. The one on the client-side works, but the one logs an "empty" object.. it just shows "{}". How do I get my data to stay in the object?
const status = "Y";
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: status
fetch('/events/<%- event.id %>/prompt', options)
console.log(options.body)
Here's my route for context:
router.route('events/:id/prompt')
.get(catchAsync(events.showPrompt))
.post(catchAsync(events.checkIn))
And my controller:
module.exports.checkIn = async(req, res) => {
console.log(req.body);
}
How do I get the object to come through to the server?
CodePudding user response:
Status is a string. However body have to take a object with key-value pair. If send like with like below, then you get object which contains status on the backend side.
body: {status: status}
CodePudding user response:
Problem from :
- Client : you choose Content-type': 'application/json' , so your body must be json format , something like body : { status } . Make sure you sent exact object with browser debug , because some call api package can change value of request.
- Server : Some nodejs framework need parse the value is sent from client before read it (Exp : app.use(express.json()) with Express)
CodePudding user response:
- "Y" isn't valid JSON. A JSON string contains either an array of values, or an object. e.g.
{"Y": 0}
or ["Y"]
- You would need to use something like
bodyParser.json()
on the server to actually convert the string representation back into an object or an array.