当我想呈现包含 js 文件上的脚本链接的 html 文件时出现错误。但是当我加载页面时,我收到此错误:Started GET "/views/script.js" .... Returning 404我的文件夹是这样的|--todolist |--main.go |--views/ |--index.html |--script.jsmain.gopackage mainimport ( "github.com/zenazn/goji" "html/template" "net/http")func renderHTMLPage(w http.ResponseWriter, path string) { t, err := template.ParseFiles(path) if err != nil { panic(err) } t.Execute(w, nil)}func Index(w http.ResponseWriter, r *http.Request) { renderHTMLPage(w, "./views/index.html")}func main() { goji.Get("/", Index) goji.Serve()}视图/index.html<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Le titre du document</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="script.js"></script><h1>To-Do List </h1><ul id="todolist"><li> Hello <button>Delete</button></li><li> Wesh <button>Delete</button></li></ul><input type="text" id="new-text" /><button id="add">Add</button> </body></html>视图/script.jsfunction addListItem() { var text = $('#new-text').val() if (text != "") { $('#todolist').append('<li>'+text+'<button id="dede" name=\"' + i + '\">Delete</button></li>') } $('#new-text').val("")}function deleteItem() { $(this).parent().remove()}$(function() { $('#add').on('click', addListItem); $("#todolist").on("click", "#dede", deleteItem)});我怎样才能让它正确加载 js 文件?创建仅使用 jquery/javascript 和 golang api 架构的应用程序的最佳方法是什么?
2 回答

UYOU
TA贡献1878条经验 获得超4个赞
您需要:
从包含的目录提供服务
/views
- 例如 goji.Get("/views/*", http.FileServer(http.Dir("/Users/matt/Desktop/views/")))`使用
http.StripPrefix
(推荐)
下面允许您将路径与目录名称分离:
func main() {
goji.Get("/views/*", http.StripPrefix("/views", http.FileServer(http.Dir("/Users/matt/Desktop/views/"))))
goji.Get("/", Index)
goji.Serve()
}
我建议不要从“根”服务 - /*。最好从专用资产路径提供服务,因为它在查看缓存、与 CDN 交互等时更容易。

繁星点点滴滴
TA贡献1803条经验 获得超3个赞
在这种特殊情况下,代码应该看起来像
goji.Get("/", Index)
goji.Get("/*", http.FileServer(http.Dir("./views")))
goji.Serve()
但我必须说将模板和静态文件保存在同一目录中以及从根目录提供静态文件是个坏主意。
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报
0/150
提交
取消