I am trying to read post data in Express.js , with using body-parser middleware. But getting follwing error
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)
My code is something like
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
});
And I am using it with following route:
app.post('/addComment', function (req, res) {
var text = req.body.text; // error on this line
res.json({"done":"yes",text:text});
});
I have tried bothy with ajax call :
$("#postComment").click(function(){
$.ajax({
url:"/addComment",
data:{text:$('.text-comment').val()},
type:'POST',
dataType:'json',
success:function(data){
console.log(data);
}
});
});
and also using postman App.
Try change .use middleware order, example:
app.use(multer()); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
If not help try without multer, if after this you can get your json body say me.
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();
}}));
Ok. Try this, if you will have json body say me.
Ok, so lets try this:
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send("bad json");
}
}}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.