节点应用

时间:2016-09-03 10:27:42

标签: node.js express

我正在尝试使用nide模块运行一个简单的节点应用程序,并使用Advance Rest Client对其进行测试。

控制台未显示任何错误。 但我在输出中没有得到任何东西。 This is the main file

This is the router file

在ARC上运行时,我得到:无法/获取数据

代码的文字版本: MainFile:

var express = require('express');
//var morgan = require('morgan');
var bodyparser = require('body-parser');

var hostname = 'localhost';
var port = '3000';

var app = express();
//app.use(morgan('dev'));

var dishRouter = express.Router();
dishRouter.use(bodyparser.json());

var allDishes = require('./dishRouter');

//For all dishes
dishRouter.route('/dishes')
.get(allDishes.dishesGet)
.delete(allDishes.dishesDelete)
.post(allDishes.dishesPost)
;

//For specific dishesDelete
dishRouter.route('/dishes/:dishid')
.get(allDishes.dishSpecificGet)
.delete(allDishes.dishSpecificDelete)
.put(allDishes.dishSpecificPut)
;

app.listen(port,hostname,function(){
    console.log('server runing properly');
});

dishRouter文件:

console.log('in dishrouter file');


module.exports.dishesGet = function(req,res,next){
    console.log('inside GET');
    res.end('Will be displaying all the dishes');
};

module.exports.dishesDelete = function(req,res,next){
    res.end('Will delete all the dishes');
};

module.exports.dishesPost = function(req,res,next){
    res.end('will add the new dishes');
};

module.exports.dishSpecificGet = function(req,res,next){
    res.end('displaying the specific dish :'+req.params.dishid);
};

module.exports.dishSpecificDelete = function(req,res,next){
    res.end('Will delete the specific dish with id : '+req.params.dishid);
};

module.exports.dishSpecificPut = function(req,res,next){
    res.write('will update the specific dish :'+req.params.dishid);
    res.end('Updating the dish with values as name : '+req.body.name);
};

1 个答案:

答案 0 :(得分:0)

根据身体解析器docs

看起来你的路由器有点坏了:

dishRouter.use(bodyParser.json())

尝试将其切换为:

app.use(bodyParser.json())

我可以建议在文件中创建路由器,在那里编写处理程序并只导出路由器。

<强>更新 这就是你忘了的:

app.use(dishRouter)

调用express.Router()时,您只需创建路由器实例,但必须将其连接到快速应用程序实例。