[英]What's wrong with my express.router().get method?
我正在尝试遵循本教程 ,作者在其中提供了示例代码:
// 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 /
我在这里做错了什么?
由于您添加了app.use('/api', router);
您的路由是router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });
然后要访问'/'
您需要使用/api/
更新 :如果您在env中设置了端口,请使用该端口,否则您应该可以使用localhost:8081 / api /访问
希望能帮助到你 !
以上评论是正确的。
您已在本地服务器中添加了前缀“ / api”,所有传入请求将为http://localhost:<port>/api/<path>
app.use('/api', router);
如果要这样访问(不带前缀) http://localhost:<port>/<path>
请将代码更新为
app.use(router);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.