Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Can't retrieve req body from api - undefined

Been stuck on this over an hour or two now >.<

I am unable to access the request body for the user api. I can get the response 'hi' back using res.send (see screenshot) but not with any req.body values. Email is coming back undefined :/

Any ideas where I am going wrong?

Content type is set to json on the postman headers.

Controller:

import asyncHandler from 'express-async-handler'

const authUser = asyncHandler(async (req, res) => {
    const { email, password } = req.body
  
    res.send('hi' + email)
    
})

export {authUser}

Route:

import express from 'express'
const router = express.Router()
import { authUser } from '../controllers/userController.js'

router.post('/login', authUser)

export default router

enter image description here

hiundefined ^

Server.js

import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js'
import productRoutes from './routes/productRoutes.js'
import userRoutes from './routes/userRoutes.js'
import colours from 'colours'
import { notFound, errorHandler} from './middleware/errorMiddleware.js'

dotenv.config()

connectDB()

const app = express()

app.use(express.json())

app.get('/', (req, res) => {
    res.send('API is running...')
})

app.use('/api/products/', productRoutes)
app.use('/api/users/', userRoutes)

app.use(notFound)
app.use(errorHandler)

const PORT = process.env.PORT || 5000

app.listen(
    PORT,
    console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold)
)

Headers: enter image description here

question from:https://stackoverflow.com/questions/65909718/cant-retrieve-req-body-from-api-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use this middleware because if you are using Express 4.16+ you can app.use(express.json())

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyparser.json());

and update your header request accept Content-Length : <calculated when request is sent> `` enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...