Reputation: 33725
I am new to NodeJS + Express development. I want to build a REST API that can receive JSON data via POST. I was able to build the API in Express and receive a json payload from a transmission from the postman software. But when I try to simulate the same behaviour with javascript's fetch()
function from a web browser, my express rest api crashes with the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (/home/johncomputer/projects/tt/node_modules/body-parser/lib/types/json.js:89:19)
at /home/johncomputer/projects/tt/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:224:16)
at done (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:215:7)
at endReadableNT (_stream_readable.js:1184:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
I only have this one file called src/app.js
in my express project:
const express = require('express')
const port = process.env.PORT
var cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
router = express.Router()
router.post('/users', async (req, res) => {
try {
console.log("+++++++++++")
console.log(req)
console.log("=========")
res.status(201).send({ "world":true })
} catch (error) {
res.status(400).send(error)
}
})
app.use(router)
app.listen(port, () => {
console.log(`Server running on port ${port}`)
})
I'm not sure if I'm using cors()
correctly, but I threw it in there to get around a pre-flight OPTIONS issue that was causing my fetch()
to generate a failed network connection error (which didn't occur for postman).
This was my javascript fetch code:
const postData = {"name":"John","email":"[email protected]","password":"chocolate-raisins!!!"};
fetch("http://johnserver.com:3000/users", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: postData
}).then((response)=>{
console.log(response);
if(!response.ok) return {}
return response.json();
}).then((result)=>{
console.log(result);return;
}).catch(function(error){
alert("Post Request Error: "+error.toString());
});
What am I doing wrong that's causing my API to fail with fetch()
but not with postman?
EDIT
The output of the response
variable from my fetch is this:
Response { type: "cors", url: "http://johnserver.com:3000/users", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
The output of the result
variable from my fetch is this:
{ }
Upvotes: 0
Views: 1323
Reputation: 159
On your fetch method please do this.
Insead of body:post Data
do --> JSON.stringify(postData)
And also on your then function first return response.json()
and then
check whatever parameters you want.
Upvotes: 1
Reputation: 3815
You're not sending valid you need to stringify your object.
fetch("http://localhost:3000/users", {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ "name": "John", "email": "[email protected]", "password": "chocolate-raisins!!!" })
}).then((response) => {
if (!response.ok) {
return {};
}
return response.json();
}).then((response) => {
console.log(response); return;
}).catch(function (error) {
alert("Post Request Error: " + error.toString());
});
Upvotes: 1