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

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

我的是一个文本输入,我在这里添加了这个答案,所以它会帮助人们。确保在解析时设置了编码!我努力让它工作,直到我给它设置了一个合适的值。

这是我在没有使用任何解析器的情况下得到的错误:

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of undefined at Function.from (buffer.js:327:9)

我们现在不必像其他人已经提到的那样在Express中使用body解析器,而只需使用app.use(Express .text());没能解决我的问题。

undefined现在变成了Object。根据Express文档,如果Content-Type不匹配(在其他情况下),请求主体将返回一个空对象({})。

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of Object at Function.from (buffer.js:327:9)

您设置的编码类型也需要正确。在我的例子中,它是文本/纯文本。您可以更改它以满足您的需要,如JSON等。我这样做了,瞧!效果好极了!

app.use(express.text({
    type: "text/plain" 
}));

其他回答

当我遇到同样的问题时,尽管我知道BodyParser已不再使用 我已经使用了app.use(express.json()) 问题是{对我来说}: 我在放置

app.use (express.json ())

App.use ('api/v1/example', example) =>{涉及路由}

一旦我重新排列这两行;

1 - app.use(express.json())

2 -应用程序(“火/v1/example”,example)

效果很好

大部分时间需要。由于缺少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())

浪费了很多时间:

这取决于客户端请求中的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'}));

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

中间件总是首先使用。

//MIDDLEWARE
app.use(bodyParser.json());
app.use(cors());    
app.use(cookieParser());

在路线之前。

//MY ROUTES
app.use("/api", authRoutes);

首先,确保在路由之前应用这个中间件(express.urlencoded)。

let app = express();

//response as Json
app.use(express.json()); 

//Parse x-www-form-urlencoded request into req.body
app.use(express.urlencoded({ extended: true }));     

app.post('/test',(req,res)=>{
    res.json(req.body);
});

代码express.urlencoded({extended:true})只响应x-www-form-urlencoded post请求,所以在ajax/XMLHttpRequest/fetch中,确保您正在发送请求。setRequestHeader(“内容类型”、“应用程序/ x-www-form-urlencoded”);头。

就是这样!