【问题标题】:app.get('/') data doesn't show in same url using app.use('/') in expressapp.get('/') 数据不会显示在相同的 url 中使用 app.use('/') 在 express
【发布时间】:2018-10-04 08:28:52
【问题描述】:

这个Link 解释了与app.useapp.get 的区别。但没有解释相同的路线问题。所以我想问我的问题。

我用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 --> Hello CodeLab

localhost:4000/ --> Html 测试(不是你好索引

我认为app.use 只是静态文件,每次app.get 调用相同的 url 时都会调用它。为什么app.get('/')在这个项目中没有显示&lt;p&gt;Hello index&lt;/p&gt;

【问题讨论】:

标签: node.js reactjs express router


【解决方案1】:

为什么app.get('/') 在这个项目中没有显示&lt;p&gt;Hello index&lt;/p&gt;

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

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

你肯定会得到&lt;p&gt;Hello index&lt;/p&gt;

原因就在幕后,app.use()app.get() 都表现得像中间件,它们在 Express 应用程序中被平等对待。出现顺序决定了先执行哪一个。

【讨论】:

  • 那么如何在 index.html 中显示“Html test”和在服务器响应中显示“Hello index”内容?
  • 两者?似乎不可能,因为服务器对每个请求只响应一次
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多