我有这个作为我的快速服务器的配置
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"
}));
首先,确保在路由之前应用这个中间件(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”);头。
就是这样!
更新2022
你可以用。
app.use (express.json ())
const express = require('express')
const app = express();
const PORT = process.env.PORT || 3001
// Calling the express.json() method for parsing
app.use(express.json())
app.listen(PORT, () => {
console.log(`============ API Gateway is open at ${PORT} ============= `)
})
Express. json()是Express中内置的中间件函数。此方法用于解析带有JSON有效负载的传入请求,并基于body解析器。
该方法返回只解析JSON并且只查看内容类型头与类型选项匹配的请求的中间件。
表达。json vs bodyParser.json