简体   繁体   English

如何在 Express JS 的所有路由上使用 static 资源提供文件?

[英]How to serve file with static resources on all routes in Express JS?

How to serve file with static resources on all routes in Express JS?如何在 Express JS 的所有路由上使用 static 资源提供文件?

I tried serving file with static resources using these line of codes,我尝试使用这些代码行使用 static 资源提供文件,

app.use(Express.static(`${this.PATH}`));
app.use(Cors());
app.use(Express.json()); 
app.get('*', (req, res) => {
    res.sendFile('./index.html',{root: path});
});

If the user visit route 'localhost/test', response is the index.html file.如果用户访问路由'localhost/test',响应为index.html文件。 Then main.js is fetched also.然后 main.js 也被获取。

So this first part is working.所以这第一部分是有效的。 However, if the user visit route 'localhost/test/testing', response is the index.html file but the main.js is not fetched correctly.但是,如果用户访问路由'localhost/test/testing',响应是 index.html 文件,但 main.js 未正确获取。 The content of main.js is index.html that makes it result to "Uncaught SyntaxError: Unexpected token '<'" main.js 的内容是 index.html 导致"Uncaught SyntaxError: Unexpected token '<'"

It seems that the most likely possibility is that you need to change the <script> tag in index.html from this:似乎最有可能的可能性是您需要从以下位置更改index.html中的<script>标记:

<script src="main.js"></script>

to this:对此:

<script src="/main.js"></script>

When you enter /test/testing in the URL bar, the browser will request that file from your server.当您在 URL 栏中输入/test/testing时,浏览器将从您的服务器请求该文件。 Your server will send back index.html .您的服务器将发回index.html Then, the browser will parse that file and see the request from this tag:然后,浏览器将解析该文件并查看来自该标签的请求:

<script src="main.js"></script>

Since there is no path on the file being requested, the browser will add the path of the current page to that file before it sends the request to the web server.由于被请求的文件没有路径,浏览器会在将请求发送到 web 服务器之前将当前页面的路径添加到该文件。 That means, it will send a request for:这意味着,它将发送请求:

/test/testing/main.js

to your web server.到您的 web 服务器。 But, your express.static() route won't find a file that matches that path.但是,您的express.static()路由不会找到与该路径匹配的文件。 Therefore, it will fall through to your res.sendFile('./index.html',{root: path});因此,它将落入您的res.sendFile('./index.html',{root: path}); and the browser will get an HTML file when it's expecting a Javascript file and will thus give you the error you report.当浏览器期待 Javascript 文件时,浏览器将得到一个 HTML 文件,因此会给您报告的错误。

I'm personally not a fan of catch all routes like you have that send index.html for anything that doesn't match something else because it can lead to very confusing bugs or problems, but if you do so, you HAVE to not use relative paths with any of your URLs in your page because they will all break when someone requests something like /test/testing .我个人不喜欢像你这样发送index.html的所有路由的粉丝,因为它可能导致非常混乱的错误或问题,但如果你这样做,你必须不使用页面中任何 URL 的相对路径,因为当有人请求/test/testing之类的内容时,它们都会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM