簡體   English   中英

無法讀取 Express for POST 中的正文參數

[英]Can't read body parameter in Express for POST

我無法使用 express 訪問請求的正文參數:

const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const app = express();
const port = 8000;

require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);


const corsOptions = {
  origin: 'http://localhost:8000'
}

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(port, () => console.log(`Listening on http://loclalhost:${port}`));

我想打的路線是: http://loclalhost:8000/api/auth/signup

在此處輸入圖像描述

在路線中,我嘗試像這樣訪問身體:

const user = new User({
      username: req.body.username,
      email: req.body.email,
      password: bcrypt.hashSync(req.body.password, 8)
});

但是我收到錯誤TypeError: Cannot read property 'username' of undefined ,我在這里做錯了什么?

我想問題不在於讀取正文解析的數據,因為它說的是用戶而不是用戶名。 能否請您分享完整的代碼。

嗯,我的猜測是您編寫代碼的順序。 想象一下代碼從上到下,因此您在解析正文之前訪問應用程序路由。 試試這樣,交換順序:

const corsOptions = {
  origin: 'http://localhost:8000'
}

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);

這也是使用 express 路由器的常用方法,例如:

const routes = require("./routes/routes.js");

app.use(routes);

一條建議
改變:
app.use(bodyParser.urlencoded({ extended: true }))

app.use(bodyParser.urlencoded({ extended: false }))
並使用x-www-form-urlencoded

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM