app.get('/') 数据不显示在同一个 url 中使用 app.use('/') 在 express

app.get('/') data doesn't show in same url using app.use('/') in express

This Link is explaining difference with app.use and app.get. But not explaining about same route problem. So I want to ask my question.

我用 create-react-app 制作了 React 项目,并在 src 文件夹中制作了服务器。当 url 是 root 时,我想在 index.html 中显示文本。所以我写了这样的代码。

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>React App</title>
  </head>
  <body>

    <p>Html test</p>

  </body>
</html>

src/server/server.js

import express from 'express';
import path from 'path';

const app = express();
const port = 4000;

app.use('/', express.static(path.join(__dirname, '../../public')));

app.get('/', (req, res) => {
    return res.send('<p>Hello index</p>');
});

app.get('/hello', (req, res) => {
    return res.send('Hello CodeLab');
});

app.listen(port, () => {
    console.log('Express is listening on port', port);
});

package.json

"babel-node": "babel-node src/server/server.js --presets es2015"

我测试,

localhost:4000/hello --> 你好 CodeLab

localhost:4000/ --> Html test (not Hello index)

我以为 app.use 只是静态文件,每次 app.get 调用相同的 url 时都会调用它。为什么app.get('/')在这个项目中不显示<p>Hello index</p>

应用程序是在 express 启动时初始化的对象。 app.use 用于设置中间件 More info

要解决此问题,只需删除路由的匹配项:

app.use(express.static(path.join(__dirname, '../../public')));

在 app.use 中使用 '/' 您必须使用 next() 方法然后 express 将转到下一个控制器。

Why app.get('/') doesn't show <p>Hello index</p> in this project?

这取决于顺序。像这样重写:

app.get('/', (req, res) => {
    return res.send('<p>Hello index</p>');
});
app.use('/', express.static(path.join(__dirname, '../../public')));

你一定会得到<p>Hello index</p>

原因就在幕后,app.use()app.get() 两者的行为就像中间件一样,它们在 Express 应用程序中受到同等对待。出现顺序决定先执行哪一个。