gpt4 book ai didi

javascript - Express 路由器无法工作

转载 作者:行者123 更新时间:2023-12-02 15:04:51 24 4
gpt4 key购买 nike

我开始学习 Node 和 Express,但目前我的一些路线无法正常工作。这是我当前正在使用的 app.js 文件

编辑:这是我更新的文件,但我仍然收到 404

var db = require('./db');

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/users', users);
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
//res.send(req.path)
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;

我无法查看的路线是“/users/userlist”,这是我的 userlist.js 路线编辑:我已将 '/users/userlist' 移至 users.js 路由

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');

/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
var params = req.params[0].split("/");
if(params.length>=2){
var newUser = new User({username: params[0], password:params[1]});
newUser.save(function(err, fluffy){
if(err)
res.send(err);
});
}
res.send('Account Created!');
});


router.get('/users/userlist', function(req, res) {
var users;
User.find(function(err, _users){
if(err)
users="ERROR";
else
users=_users;
});
res.send(users);
});

module.exports = router;

当我尝试将浏览器指向 http://localhost:3000/users/userlist 时我刚刚收到 404。

最佳答案

您在 app.js 中声明路由时犯了一个错误,请删除以下代码。

app.use('/users/userlist',userlist);

关于javascript - Express 路由器无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com