我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

简单的例子,通过所有:

方法='post'登录后的快捷代码:

这将不需要任何这样的bodyParser()。

app.js

const express = require('express');
const mongoose = require('mongoose');
const mongoDB = require('mongodb');

const app = express();

app.set('view engine', 'ejs');

app.get('/admin', (req,res) => {
 res.render('admin');
});

app.post('/admin', (req,res) => {
 console.log(JSON.stringify(req.body.name));
 res.send(JSON.stringify(req.body.name));
});

app.listen(3000, () => {
 console.log('listening on 3000');
});

admin.ejs

<!DOCTYPE Html>
<html>
 <head>
  <title>Admin Login</title>
 </head>
 <body>
   <div>
    <center padding="100px">
       <form method="post" action="/admin">
          <div> Secret Key:
            <input name='name'></input>
          </div><br></br><br></br>
          <div>
            <button type="submit" onClick='smsAPI()'>Get OTP</button>
          </div>
       </form>
    </center>
    </div >
</body>
</html>

你得到输入。“”中的“name”是一个通过method='post'传递数据的变量。对于多个数据输入,name='name[]'。

因此,

on name='name' 

input: Adu
backend: "Adu"

OR

input: Adu, Luv,
backend: "Adu, Luv,"

on

name='name[]'
input: Adu,45689, ugghb, Luv
backend: ["Adu,45689, ugghb, Luv"]

其他回答

You have to check following things for that:-
1. app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Implement body parser in your app.

2. Check headers in postman its should be based on your rest api's, like if your Content-Type: application/json it should be defined in your postman headers.

在express 4及以上版本中,你不需要body解析器,它们有自己的json解析方法, 在您的express应用程序的高设置级别添加

var express = require('express');
var app = express()
app.use(express.json()); //declare this to receive json objects.

其他答案没有提到,当通过fetch或其他客户端进行表达请求时。请求必须以某种方式格式化。

const response = await fetch(`${expressAddress}/controller/route`, { 
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      headers: {
          'Content-Type': 'application/json' //this must be set to a json type
      },
      body: JSON.stringify(row) //regular js object need to be converted to json
  })

如果你像这样进行取回请求。Body将按预期输出json对象。

浪费了很多时间:

这取决于客户端请求中的Content-Type 服务器应该有不同的,以下app.use()之一:

app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))

来源:https://www.npmjs.com/package/body-parser bodyparsertextoptions

例子:

对我来说, 在客户端,我有以下标题:

Content-Type: "text/xml"

因此,在服务器端,我使用:

app.use(bodyParser.text({type: 'text/xml'}));

然后,要求。身体工作正常。

大部分时间需要。由于缺少JSON解析器,body未定义

const express = require('express');
app.use(express.json());

可能缺少体解析器

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

有时由于cros原点没有定义,所以加起来

const cors = require('cors');
app.use(cors())

最新版本的Express已经内置了体解析器。所以你可以用:

const express = require('express);
... 
app.use(express.urlencoded({ extended: false }))
.use(express.json());