I created a simple Node & Express server to catch a POST request and to send the request body as a response. And it is perfectly working on postman below is a screenshot of working request on the postman,
So this is the response i get in Postman
And here is my backend code.
const express = require('express')
const app = express()
app.listen(3000, () => console.log('listening at port 3000'))
app.use(express.static('public'))
app.use(express.json())
app.post('/api/', (req, res) => {
console.log('A post request have recieved')
console.log(req.body)
res.send('This is the body of that POST request' JSON.stringify(req.body))
})
But when I try to create that same POST request using fetch with an HTML button, the received request body (which I have sent with fetch) becomes null.
Here is the HTML,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>fetcher</title>
</head>
<body>
<input value="click" id="btn" type="button" onclick="buttonFunc()" />
<script src="main.js"></script>
</body>
</html>
And here is the javascript for that,
function buttonFunc() {
const data = {
name: 'john',
}
console.log('clicked')
const options = {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}
fetch('http://localhost:3000/api/', options)
.then(function (response) {
console.log(response.body)
})
.catch(function (error) {
console.error(error)
})
}
I can't find any mistakes in my code. Can anyone please help me to figure it out ?
I'll also attach a screenshot from my browser.
Browser response with null as body
And here are some screenshots for a total response.
CodePudding user response:
You need to convert the response to json
fetch('http://localhost:3000/api/', options)
.then(response => response.json())
.then(json => {
console.log(json)
})
.catch(function (error) {
console.error(error)
})
CodePudding user response:
Try changing your code to send response like below:
app.post('/api/', (req, res) => {
console.log('A post request have recieved')
console.log(req.body)
var resData = {
status: 1,
message: "Success",
data: req.body
};
return res.status(200).json(resData);
})