當我想呈現(xiàn)包含 js 文件上的腳本鏈接的 html 文件時出現(xiàn)錯誤。但是當我加載頁面時,我收到此錯誤: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 文件?創(chuàng)建僅使用 jquery/javascript 和 golang api 架構(gòu)的應(yīng)用程序的最佳方法是什么?
2 回答

UYOU
TA貢獻1878條經(jīng)驗 獲得超4個贊
您需要:
從包含的目錄提供服務(wù)
/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()
}
我建議不要從“根”服務(wù) - /*。最好從專用資產(chǎn)路徑提供服務(wù),因為它在查看緩存、與 CDN 交互等時更容易。

繁星點點滴滴
TA貢獻1803條經(jīng)驗 獲得超3個贊
在這種特殊情況下,代碼應(yīng)該看起來像
goji.Get("/", Index)
goji.Get("/*", http.FileServer(http.Dir("./views")))
goji.Serve()
但我必須說將模板和靜態(tài)文件保存在同一目錄中以及從根目錄提供靜態(tài)文件是個壞主意。
- 2 回答
- 0 關(guān)注
- 195 瀏覽
添加回答
舉報
0/150
提交
取消