我正在嘗試制作一個SPA Web應用程序,并從大猩猩復用器包中獲取此示例 https://github.com/gorilla/mux#serving-single-page-applications 但是在我對路徑進行了一些更改之前,它不起作用,就像那里描述的那樣 https://github.com/gorilla/mux/issues/588當我在瀏覽器中打開一些路徑 http://localhost:8080/somepage 它提供索引.html和相關文件(css和js)。但是如果我用另一個斜杠輸入路徑,例如 http://localhost:8080/somepage/smt 它也提供索引.html但js和css不起作用,并且它們的代碼被更改為索引.html中的代碼。因此,我的js或css文件具有與索引.html完全相同的代碼。我不知道為什么會這樣,以及軟件包的示例是如何工作的。這是我的代碼func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { path, err := filepath.Abs(r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } path = filepath.Join(h.staticPath, r.URL.Path) _, err = os.Stat(path) if os.IsNotExist(err) { //this called if the path is like that http://localhost:8080/any or ...any/somesubpage http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath)) return } else if err != nil { fmt.Println("500") http.Error(w, err.Error(), http.StatusInternalServerError) return } //this called if the path is just http://localhost:8080 http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)}func main() { router := mux.NewRouter() //api handlers spa := spaHandler{staticPath: "./", indexPath: "index.html"} router.PathPrefix("/").Handler(spa) srv := &http.Server{ Handler: router, Addr: "127.0.0.1:8080", } log.Fatal(srv.ListenAndServe())}staticPath 是 ./ 因為如果我的索引.html在某個文件夾中,這絕對不起作用。我在Ubuntu中使用了這個示例,沒有進行任何更改,并且效果很好。也許是因為文件路徑工作的差異。但我在Windows上需要它?;蛘咭苍S還有其他方法可以使水療在圍棋中?
1 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
如果請求的文件不存在,您的代碼將返回;例如,如果請求是 for(并且該路徑中沒有),則將返回該文件。問題是,如果包含(或),則腳本標記將導致瀏覽器請求(因為路徑是相對的,并且原始請求的路徑是),并且這將不會返回預期的文件(將返回,因為請求的文件不存在!index.html
http://address.com/foo/bar/xxx.html
xxx.html
index.html
index.html
<script src="test.js"></script>
src=./test.js
http://address.com/foo/bar/test.js
/foo/bar/
index.html
將 html 更改為使用絕對路徑(例如 )意味著無論原始請求路徑如何,都將請求正確的 javascript(或其他文件類型)。<script src="/test.js"></script>
- 1 回答
- 0 關注
- 96 瀏覽
添加回答
舉報
0/150
提交
取消