为什么我在此URL上收到404错误?

时间:2018-08-15 02:40:03

标签: javascript node.js node-modules

有人可以告诉我为什么在URL中键入404时出现\book错误吗?

这是我的代码:

var express = require('express'),
    app = express(),
    chalk = require('chalk'),
    debug = require('debug')('app'),
    morgan = require('morgan'),
    path = require('path'),
    PORT = process.env.PORT || 3000;


app.use(morgan('tiny'));
const bookRoutes = require('./routes/bookroutes');

app.use(express.static(path.join(__dirname,'/public')));
app.use('/css',express.static(path.join(__dirname,'/node_modules/bootstrap/dist/css')))
app.use('/js',express.static(path.join(__dirname,'/node_modules/bootstrap/dist/js')))
app.use('/js',express.static(path.join(__dirname,'/node_modules/jquery/dist')))

app.use('book',bookRoutes);
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '/views/index.html'))
});


app.listen(PORT, () => {
    debug(`listing to ${chalk.red(PORT)}`);

});

bookroutes.js

var express = require('express');
var bookRoutes = express.Router();

bookRoutes.route('/', (req, res) => {
    console.log('book')
    res.send('book')
});

module.exports = bookRoutes;

当我在浏览器URL中输入http://localhost:3000/book时,它将显示以下错误:

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
  app listing to 3000 +0ms
GET /worker.js 404 148 - 7.814 ms
GET /book 404 143 - 1.021 ms

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题。您在路线定义中缺少/

app.use('/book', bookRoutes);

bookRoutes.js内,您必须使用get对象上的router方法来定义/book GET请求的处理程序。

bookRoutes.get('/', (req, res) => {
  res.send('book');
});

有关更多信息,请检查documentation