简体   繁体   English

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

[英]Why am I getting a 404 error on this URL?

Could anyone please tell me why I am getting a 404 error when I type \\book in the URL?谁能告诉我为什么在 URL 中输入\\book时会出现404错误?

Here is my code:这是我的代码:

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)}`);

});

And bookroutes.js :bookroutes.js

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

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

module.exports = bookRoutes;

When I enter http://localhost:3000/book in the browser URL, it will show these errors:当我在浏览器 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

There are a couple of issues with your code.您的代码有几个问题。 You're missing a / in your route definition.您的路由定义中缺少/

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

And inside bookRoutes.js , you've to make use of the get method on the router object to define a handler for GET /book endpoint.bookRoutes.js ,您必须使用router对象上的get方法来定义GET /book端点的处理程序。

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

For more info, check the documentation .有关更多信息,请查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM