Node.js 如何在Express.js中读取post数据
我正在尝试使用主体解析器中间件读取Express.js中的post数据。但是接下来的错误Node.js 如何在Express.js中读取post数据,node.js,post,express,body-parser,Node.js,Post,Express,Body Parser,我正在尝试使用主体解析器中间件读取Express.js中的post数据。但是接下来的错误 TypeError: Cannot read property 'text' of undefined at /var/www/html/forkom/routes/index.js:49:28 at callbacks (/var/www/html/forkom/node_modules/express/lib/router/index.js:272:11) at param (/var/www/html
TypeError: Cannot read property 'text' of undefined
at /var/www/html/forkom/routes/index.js:49:28
at callbacks (/var/www/html/forkom/node_modules/express/lib/router/index.js:272:11)
at param (/var/www/html/forkom/node_modules/express/lib/router/index.js:246:11)
我的代码类似于
var express = require('express'), routes = require('./routes');
var app = express.createServer();
var bodyParser = require('body-parser');
var multer = require('multer');
require('./routes/index')(app); // use route
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.configure('production', function(){
app.use(express.errorHandler());
app.use(app.router);
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer()); // for parsing multipart/form-data
});
我使用它的路线如下:
app.post('/addComment', function (req, res) {
var text = req.body.text; // error on this line
res.json({"done":"yes",text:text});
});
我尝试过bothy和ajax调用:
$("#postComment").click(function(){
$.ajax({
url:"/addComment",
data:{text:$('.text-comment').val()},
type:'POST',
dataType:'json',
success:function(data){
console.log(data);
}
});
});
也可以使用postman应用程序。尝试更改。使用中间件顺序,例如:
app.use(multer()); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
如果没有multer帮忙试试,如果在这之后你可以让你的json身体告诉我
app.use(multer({inMemory: true, onParseEnd: function(req, next){
for(var file in req.files){
if (file != 'archive'){
req.body = JSON.parse(req.files[file].buffer);
}
}
return next();
}}));
嗯。试试这个,如果你想告诉我的话
app.use(multer({inMemory: true, onParseEnd: function(req, next){
for(var file in req.files){
if (file != 'archive'){
req.body = JSON.parse(req.files[file].buffer);
}
}
return next();
}}));
好的,让我们试试这个:
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send("bad json");
}
}}));
如何发布数据?请参阅编辑后的文章。您是否在
生产模式下运行此操作?因为您仅在生产环境中配置。此外,尝试放置app.use(app.router)代码>在应用程序之后使用(multer())代码>确定,在发送ajax JSON.stringify(数据:{text:$('.text comment').val())之前,尝试将正文字符串化;