working post request on postman
Above in Postman, I'm sending the same post request with same body in json type and it's working perfectly in Postman and sending back the user id as response.
But when I try to send the same request using fetch request.body become undefined.
This is my frontend fetch request.
fetch('http://localhost:3000/api/user/register', {
method: 'post',
mode: 'no-cors', // no-cors, *cors, same-origin
body: formJSON,
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
return response.text()
})
.then(function (text) {
console.log(text)
})
.catch(function (error) {
console.error(error)
})
And this is my backend code
const router = require('express').Router()
const User = require('../model/User')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const { registerValidation, loginValidation } = require('../validation')
const { request } = require('express')
router.post('/register', async (req, res) => {
console.log(request.body)
//validating
const { error } = registerValidation(req.body)
if (error) return res.status(400).send(error.details[0].message)
//check if email already exist
const emailExist = await User.findOne({ email: req.body.email })
if (emailExist) return res.status(400).send('Email is taken')
//hashing password
const salt = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(req.body.password, salt)
//create user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
})
try {
const savedUser = await user.save()
res.send({ user: user._id })
} catch (err) {
res.status(400).send(err)
}
})