【发布时间】:2018-10-04 08:28:52
【问题描述】:
这个Link 解释了与
app.use和app.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('/')在这个项目中没有显示<p>Hello index</p>?
【问题讨论】:
-
交换订单。排在第一位的人获得奖品
标签: node.js reactjs express router