节点和快速路由 - 404 错误
Node and Express Routing - 404 error
我在使用 nodemon 时返回 404 错误,但不太确定问题出在哪里。感谢任何提示/资源!
项目根目录
$ curl http://127.0.0.1:3000/v1/protected
Cannot GET /v1/protected
nodemon: "GET /v1/protected/ HTTP/1.1" 404 26 "-" "curl/7.49.1"
index.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
var router = require('./services/router');
mongoose.connect('mongodb://localhost:introToBackend/introToBackend');
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(express('/v1', router));
const PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';
console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);
services/router.js
var router = require('express').Router();
function protectedRoute(req, res, next) {
res.send("The secret!");
}
router.route('/protected')
.get(protectedRoute);
module.exports = router;
尝试写作
express.use('/v1',你的路由器);
你不需要app.use
里面的快递
我在使用 nodemon 时返回 404 错误,但不太确定问题出在哪里。感谢任何提示/资源!
项目根目录
$ curl http://127.0.0.1:3000/v1/protected
Cannot GET /v1/protected
nodemon: "GET /v1/protected/ HTTP/1.1" 404 26 "-" "curl/7.49.1"
index.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
var router = require('./services/router');
mongoose.connect('mongodb://localhost:introToBackend/introToBackend');
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(express('/v1', router));
const PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';
console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);
services/router.js
var router = require('express').Router();
function protectedRoute(req, res, next) {
res.send("The secret!");
}
router.route('/protected')
.get(protectedRoute);
module.exports = router;
尝试写作 express.use('/v1',你的路由器); 你不需要app.use
里面的快递