我正在尝试在nodejs中创建一个api。
我的server.js文件正在关注
var http = require('http'),
path = require('path'),
async = require('async'),
socketio = require('socket.io'),
express = require('express'),
session = require('express-session'),
logger = require('morgan'),
bodyParser = require('body-parser');
var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);
app.use(logger('dev'));
app.use(bodyParser.json());
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
app.all('/api/*', [require('./middlewares/validateRequest')]);
//app.use(express.static(path.resolve(__dirname, 'client')));
app.use('/', require('./routes'));
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var messages = [];
var sockets = [];
......
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Meeting Panel listening at", addr.address + ":" + addr.port);
});
my / routes dir有index.js文件
var express = require('express');
var router = express.Router();
var auth = require('./auth.js');
var meetings = require('./meetings.js');
var user = require('./users.js');
/*
* Routes that can be accessed by any one
*/
router.post( '/login', auth.login);
/*
* Routes that can be accessed only by authenticated & authorized users
*/
router.get('/api/admin/users', user.getAll);
.....
.....
module.exports = router;
现在,当我打开/ login页面时,我收到以下错误
Error: Not Found
at /home/ubuntu/workspace/server.js:46:15
at Layer.handle [as handle_request] (/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:312:13)
at /home/ubuntu/workspace/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:330:12)
at next (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:271:10)
at /home/ubuntu/workspace/node_modules/express/lib/router/index.js:618:15
at next (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:176:3)
at router (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:46:12)
答案 0 :(得分:1)
您在/login
上的路线是在POST方法上定义的。如果你想从浏览器打开它(我假设你正在做的事情),你应该定义router.get( '/login'...
。我想您不希望在GET方法上定义/login
路由,因此您测试的另一个好选择是点击/api/admin/users
。
答案 1 :(得分:1)
如果您只是在浏览器中打开http://example/login,那将是一个获取请求,所以在这种情况下,它将找不到您正在收听帖子/登录而不是/登录的路线。