节点Js表示路由器不工作

时间:2017-02-13 02:20:30

标签: javascript node.js web-services express

js和我正在学习节点js和express,我正在学习快速路由我在rest.js中有以下代码

    const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');

const app1 = express(); 

const server = http.createServer(app1);



app1.get('/api',widgetRouter);


server.listen(3000,function(){
    console.log('server started in port 3000');

});



const app = express();

我也有widgets.js文件

const express = require('express');

const widgetRouter = express.Router();

widgetRouter.route("/widgets")
    .get(function(req,res){
        res.json({"abc":"hello"});
    })
    .post();

widgetRouter.route("/widgets/:widgetId")
    .get()
    .put()
    .delete();



module.exports = widgetRouter;

但当我尝试从邮递员那里测试其余的api(http://localhost:3000/api/widgets)时,它说不能GET / api / widgets

2 个答案:

答案 0 :(得分:6)

您已导入并初始化 express 模块,但随后您使用 http 模块启动服务器。你应该只使用Express:

此外,您应该使用app.use('/api',widgetRouter)代替app.get('/api', widgetRouter)这是一个快速中间件。

const express = require('express');
const app = express(); 

const widgetRouter = require('./rest/widgets');

app.use('/api', widgetRouter);
app.get('/', function(req, res) {
    res.send('Home');
});

app.listen(3000, function(){
    console.log('server started in port 3000');
});

答案 1 :(得分:1)

你也可以试试。

rest.js

const express = require('express');
const http = require('http');
const  router = express.Router();

const app = express();

require('./widgets')(app, router);

app.get('/', function(req, res) {
    res.send('Home');
});

app.listen(3000,function(){
    console.log('server started in port 3000');
});

widgets.js

module.exports = function(app, router){
    router.route("/widgets")
        .get(function(req,res){
            res.json({"abc":"hello"});
        })
        .post();

    router.route("/widgets/:widgetId")
        .get()
        .put()
        .delete();

    app.use('/api', router);
});