簡體   English   中英

為什么我在此 URL 上收到 404 錯誤?

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

誰能告訴我為什么在 URL 中輸入\\book時會出現404錯誤?

這是我的代碼:

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

您的代碼有幾個問題。 您的路由定義中缺少/

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

bookRoutes.js ,您必須使用router對象上的get方法來定義GET /book端點的處理程序。

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

有關更多信息,請查看文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM