无法使用带点的相对路径加载Javascript文件

minecraftplayer1234:

所以我确实有这个项目结构:

在此处输入图片说明

index.html我写的HTML 文件:

<!DOCTYPE html>
<html>

<body>

    <head>
        XD
    </head>
    <script type="text/javascript" src="../static/js/app.js"></script>
    <button type="button" onclick="XD()">
        XD</button>
</body>

</html>

app.js 文件:

function XD() {
    console.log("XD")
}

最后main.go

package main

import (
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir("tmpl")))
    http.ListenAndServe(":8080", nil)
}

在构建并运行应用程序(具有来自防火墙等所有权限的应用程序)后,当我转到localhost:8080带有标题和按钮加载的页面时。但是在开发控制台中,我可以看到以下消息:

GET http://localhost:8080/static/js/app.js [HTTP/1.1 404 Not Found 3ms]
The resource from “http://localhost:8080/static/js/app.js” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

好吧,我认为这可能与错误的相对路径有关(尽管当我按Ctrl + LeftClick时,VSCode会将我准确地保存到app.js文件中)。我将app.js文件移动tmpl/dir,并将路径更改index.html为just src="app.js"出乎意料的是,它可以正常工作,XD并被打印到控制台中。现在我做错什么了吗?还是.js文件应该与文件位于同一目录树中.html

列宁哈斯达:

没错 问题是您可以从Web tmpl目录访问唯一的目录。

http.Handle("/", http.FileServer(http.Dir("tmpl")))

因此,当您键入localhost:8080内容时,基本上是从该目录浏览文件,而静态文件不存在。但是,当您将app.js文件移动tmpl目录时,它可以工作,因为现在可以从Web上访问它了。

因此,您只需要将静态内容包含在tmpl更精确的Web可访问目录中即可。

更新资料

上面的解决方案描述了如何serve从单个目录中文件(html,css,js等)。
另一种方法是serve只处理静态文件(css,js等)和render模板(html)。您可以像现在一样为静态文件和模板设置不同的文件夹。

main.go文件中

func main() {
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.HandleFunc("/", indexHandler)
    http.ListenAndServe(":5000", nil)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    tpl, _ := ioutil.ReadFile("./tmpl/index.html")
    tplParsed, _ := template.New("test").Parse(string(tpl))
    tplParsed.Execute(w, nil)
}

在这里,我们在http://localhost:5000/static端点中提供静态文件所以在您的index.html文件app.js链接应该是/static/js/app.js

请注意,我们不是直接提供html文件,而是使用http / template package渲染它同样,您也可以渲染其他模板文件。希望对您有所帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章