gpt4 book ai didi

javascript - Node.js 有时会出现链接脚本问题

转载 作者:行者123 更新时间:2023-12-02 21:19:05 24 4
gpt4 key购买 nike

你好,我创建了 SPA 客户端 - 这里一切正常(使用普通路由器)

但是服务器node.js在尝试加载链接脚本时有时会给我错误

Uncaught SyntaxError: Unexpected token '<'

仅当我在网址 (/) 中使用多个反斜杠时才会出现错误。

例如

localhost:3000 - is okay (script loaded)

localhost:3000/test - is okay

localhost:3000/about - is okay

localhost:3000/test/test - Error

localhost:3000/profile/user - Error

我的服务器代码

app.use(express.static(__dirname + '/dist'));

app.get('*', function(req, res){
res.sendFile(path.resolve(__dirname, 'index.html'));
});

在 dist 文件夹中我有 test.js 脚本

我的代码来自index.html

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

最佳答案

<script src="test.js" ></script>时在你的前端,它会尝试从“当前文件夹”中获取,所以如果你在页面 localhost:3000/test/test它将尝试加载 localhost:3000/test/test.js这意味着您的后端将寻找 dist/test/test.js ,它可能不存在,从而导致它加载您的索引页(向您提供有关意外 < 的错误消息)。

更改您的前端以使用:

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

注意前面添加的斜杠,这意味着它将尝试从根加载,即无论您在前端的哪个页面,它都会加载 localhost:3000/test.js

关于javascript - Node.js 有时会出现链接脚本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60896113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com