-1

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)
  }
}) 
Shaheer.K
  • 1
  • 4
  • What is `formJSON`? Is it a JSON string or a JavaScript object? Also, it doesn't look like you should be using `mode: "no-cors"` if you want to actually interact with the response data. Since you control the backend too, just apply the [cors middleware](https://www.npmjs.com/package/cors) – Phil Aug 23 '21 at 03:45
  • Does this answer your question? [Fetch: POST JSON data](https://stackoverflow.com/questions/29775797/fetch-post-json-data). And this? [Trying to use fetch and pass in mode: no-cors](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors). And this? [What is an opaque response, and what purpose does it serve?](https://stackoverflow.com/questions/36292537/what-is-an-opaque-response-and-what-purpose-does-it-serve) – Phil Aug 23 '21 at 03:48

1 Answers1

0

you must stringify your body.

 {
    method: 'post',
    mode: 'no-cors', // no-cors, *cors, same-origin
    body: JSON.stringify(formJSON),
    headers: {
      'Content-Type': 'application/json',
 },