【问题标题】:request.body that recieved by the server is undifind which is sent by fetch服务器接收到的 request.body 未定义,由 fetch 发送
【发布时间】:2021-10-23 10:47:43
【问题描述】:

working post request on postman

在 Postman 的上方,我正在发送相同的 json 类型的正文请求,它在 Postman 中运行良好,并将用户 ID 作为响应发送回。

但是当我尝试使用 fetch request.body 发送相同的请求时,会变成 undefined

这是我的前端获取请求。


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)
    }) 

这是我的后端代码

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)
  }
}) 

【问题讨论】:

标签: node.js express post fetch postman


【解决方案1】:

你必须把你的身体串起来。

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

【讨论】:

  • 我有 JSON.stringify 在创建获取请求之前。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多