Node.js app.get(';/';)数据不';使用app.use(';/';)无法在同一url中显示
这解释了Node.js app.get(';/';)数据不';使用app.use(';/';)无法在同一url中显示,node.js,reactjs,express,router,Node.js,Reactjs,Express,Router,这解释了app.use和app.get的区别。但没有解释同样的路线问题。所以我想问我的问题 我用createreact-app创建了react项目,并在src文件夹中创建了服务器。当url为root时,我想在index.html中显示文本。所以我写了这样的代码 public/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <
app.use
和app.get
的区别。但没有解释同样的路线问题。所以我想问我的问题
我用createreact-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>
我测试
localhost:4000/hello
-->hello CodeLab
localhost:4000/
-->Html测试(非Hello索引)
我认为
app.use
只是一个静态文件,每当app.get
调用同一个url时,它都会被调用。为什么app.get('/')
在此项目中不显示Hello index
?应用程序是在express开始时初始化的对象。app.use用于设置中间件
要解决此问题,只需删除路由的匹配项:
app.use(express.static(path.join(__dirname, '../../public')));
使用app.use中的“/”时,必须使用next()方法,然后express将转到下一个控制器
为什么app.get('/')
在此项目中不显示Hello index
这取决于顺序。重新这样写:
app.get('/', (req, res) => {
return res.send('<p>Hello index</p>');
});
app.use('/', express.static(path.join(__dirname, '../../public')));
app.get('/',(req,res)=>{
返回res.send(“Hello index”);
});
app.use('/',express.static(path.join(uu dirname,../public'));
你肯定会得到Hello索引
原因就在幕后,
app.use()
和app.get()
两者的行为就像中间产品一样,在Express应用程序中受到同等对待。显示顺序决定先执行哪一个。交换顺序。第一行获取可能的副本,然后如何在index.Html中显示“Html测试”内容和在服务器响应中显示“Hello索引”内容?两者都有?这似乎不可能,因为服务器对每个请求只响应一次
app.use(express.static(path.join(__dirname, '../../public')));
app.get('/', (req, res) => {
return res.send('<p>Hello index</p>');
});
app.use('/', express.static(path.join(__dirname, '../../public')));