express.js路由返回404

时间:2018-12-19 15:27:35

标签: node.js express routing

我正在学习nodejs,我从express开始,但是当我创建一个名为movie的路由时,它返回404错误。但是我从Express Generator的index.js复制了它,那么问题出在哪里?

movie.js

    import express from 'express';

const router = express.Router();

/* GET index page. */
router.get('/movie', (req, res) => {
    res.render('index', {
        title: 'Express'
    });
});

export default router;

编辑1

app.js

import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import Debug from 'debug';
import express from 'express';
import logger from 'morgan';
import path from 'path';
// import favicon from 'serve-favicon';
import { middleware as stylusMiddleware } from 'stylus';

import index from './routes/index';

const app = express();
const debug = Debug('movie-book:app');
import movie from  './routes/movie';

app.set('views', path.join(__dirname, 'views'));

// db connection
const db = require('./helper/db.js')();
// view engine setup
app.set('view engine', 'pug');
// 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(stylusMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/api/movie', movie);

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

// error handler
/* eslint no-unused-vars: 0 */
app.use((err, req, res, next) => {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

// Handle uncaughtException
process.on('uncaughtException', (err) => {
    debug('Caught exception: %j', err);
    process.exit(1);
});

export default app;

2 个答案:

答案 0 :(得分:0)

您添加了路由器吗?

import media from './routes/media';
const app = express();
/**
 * Add routes
 */
app.use('/media', media);

https://expressjs.com/en/guide/routing.html(请参阅页面结尾)

https://expressjs.com/en/4x/api.html#app.use

答案 1 :(得分:0)

确保在app.js文件中使用相同的网址,并且您输入的网址正确。    如果您是由Express Generator创建的项目:-

//Changes in app.js
var indexRouter = require('./routes/index');

app.use('/', indexRouter);
//change above line into below
app.use('/movie', indexRouter);

有关路由的参考:Express