使用Node.js通过Postman通过REST API发布数据时出现以下错误我在下面提供我的代码。
server.js:
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var app=express();
var server=http.Server(app);
var port=8080;
require('./route/route.js')(app);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'})) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
app.get('/',function(req,res){
res.json({"message": "Task management application."});
})
server.listen(port);
console.log("Server is running on the port"+port);
路线/ route.js:
var task=require('../controller/controller.js');
module.exports = function(app) {
app.post('/signup',task.userSignup);
}
控制器/ controller.js:
var mongoJs=require('mongojs');
var database='TASK';
var collections=['f_users'];
var db=mongoJs("127.0.0.1:27017/"+database, collections);
db.on('connect', function () {
console.log('database connected')
});
exports.userSignup=function(req,res){
console.log('req',req);
var username=req.body.username;
var password=req.body.password;
var phone=req.body.phone;
db.f_users.insert({'username':username,'password':password,'phone':phone},function(err,docs){
if (!err) {
if (docs) {
res.json({'message':'User has registered successfully'});
}
}
})
}
我正在做如下的帖子。
这里我在发布数据时收到以下错误。
TypeError: Cannot read property 'username' of undefined
<br> at exports.userSignup (C:\xampp\htdocs\bigdata\controller\controller.js:10:23)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:131:13)
<br> at Route.dispatch (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\route.js:112:3)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
<br> at C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:277:22
<br> at Function.process_params (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:330:12)
<br> at next (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\index.js:271:10)
<br> at expressInit (C:\xampp\htdocs\bigdata\node_modules\express\lib\middleware\init.js:33:5)
<br> at Layer.handle [as handle_request] (C:\xampp\htdocs\bigdata\node_modules\express\lib\router\layer.js:95:5)
如何解决此错误并成功保存数据?