我的express.router()。get方法有什么问题?

时间:2016-06-06 04:06:39

标签: javascript node.js express

我正在尝试follow this tutorial,其中作者提供了示例代码:

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

我调整了一下,这是我的代码:

'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8081;

var router = express.Router();

router.get('/', function(req, res, next) {
  res.json({ message: 'Hello World!' });
});

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


app.listen(port);
console.log('Magic happens on port ' + port);

服务器运行正常,但当我访问localhost:8081时,我在浏览器上收到以下消息:Cannot GET /

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

由于您添加了app.use('/api', router);

您的路线为router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });

然后要访问'/',您需要使用/api/

进行申请

更新:如果您在env中设置了端口,请使用该端口,否则您应该可以使用localhost:8081/api/

进行访问

希望它有所帮助!

答案 1 :(得分:0)

以上评论是正确的。

您添加了前缀&#39; / api&#39;到您的本地服务器,所有传入的请求都是http://localhost:<port>/api/<path>

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

如果你想这样访问(没有前缀)http://localhost:<port>/<path> 请将您的代码更新为

app.use(router);