該賞金過期5天。此問題的答案有資格獲得 100聲望獎勵。 沙菲克·賈馬爾希望引起對這個問題的更多關注。
我按照這個示例使用 Golang 和本機net/http包為 NextJs 前端單頁應用程式提供服務:
import (
"embed"
"io/fs"
"log"
"net/http"
"runtime/pprof"
)
//go:embed nextjs/dist
//go:embed nextjs/dist/_next
//go:embed nextjs/dist/_next/static/chunks/pages/*.js
//go:embed nextjs/dist/_next/static/*/*.js
var nextFS embed.FS
func main() {
// Root at the `dist` folder generated by the Next.js app.
distFS, err := fs.Sub(nextFS, "nextjs/dist")
if err != nil {
log.Fatal(err)
}
// The static Next.js app will be served under `/`.
http.Handle("/", http.FileServer(http.FS(distFS)))
// The API will be served under `/api`.
http.HandleFunc("/api", handleAPI)
// Start HTTP server at :8080.
log.Println("Starting HTTP server at http://localhost:8080 ...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
它有效。現在我想使用gorilla/mux而不是本機net/http包。所以現在我的main函式看起來像這樣:
func main() {
// Root at the `dist` folder generated by the Next.js app.
distFS, err := fs.Sub(nextFS, "nextjs/dist")
if err != nil {
log.Fatal(err)
}
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.FS(distFS)))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:8080",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
這適用于index.html file當我localhost:8080在瀏覽器中導航時提供服務,但該頁面沒有樣式、沒有影像,也沒有 JavaScript。
我嘗試使用gorilla/muxSPA 服務中的說明,但對于此Next.js應用程式,它無法找到檔案,并且瀏覽器會因連接重置錯誤而出錯。
我還需要做什么才能在頁面加載時使用 CSS、JavaScript 和影像?
uj5u.com熱心網友回復:
請試試
r.PathPrefix("/").Handler(http.FileServer(http.FS(distFS)))
gorilla/mux 將Handle函式的第一個引數解釋為模板:https : //pkg.go.dev/github.com/gorilla/mux#Route.Path。
請注意添加路由時的順序:當兩條路由匹配相同的路徑時,第一個添加的獲勝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400786.html
