programing

실제 가동 중인 vue-router(Go와 함께 사용)

sourcejob 2022. 8. 12. 23:09
반응형

실제 가동 중인 vue-router(Go와 함께 사용)

클라이언트와 서버를 완전히 분리하고 싶어서 vuejs 프로젝트를 만들었습니다.vue init webpack my-project이 프로젝트에서는 모든 라우팅에 vue-router를 사용합니다(이것에는 다음과 같은 특별한 경로가 포함됩니다)./user/SOMEID..

다음은 my routes.js 파일입니다.

import App from './App.vue'

export const routes = [
  {
    path: '/',
    component: App.components.home
  },
  {
    path: '/user/:id',
    component: App.components.userid
  },
  {
    path: '*',
    component: App.components.notFound
  }
]

응용 프로그램을 실행할 때npm run dev모든 것이 완벽하게 작동한다.이제 클라우드에 도입할 준비가 되었기 때문에npm run buildHTTP 서버를 사용해야 하기 때문에 Go를 사용하기로 했습니다.이것은 나의 바둑 파일입니다.

package main

import (
    "fmt"
    "github.com/go-chi/chi"
    "github.com/me/myproject/server/handler"
    "net/http"
    "strings"
)

func main() {
    r := chi.NewRouter()

    distDir := "/home/me/code/go/src/github.com/me/myproject/client/dist/static"
    FileServer(r, "/static", http.Dir(distDir))

    r.Get("/", IndexGET)

    http.ListenAndServe(":8080", r)
}

func IndexGET(w http.ResponseWriter, r *http.Request) {
    handler.Render.HTML(w, http.StatusOK, "index", map[string]interface{}{})
}

func FileServer(r chi.Router, path string, root http.FileSystem) {
    if strings.ContainsAny(path, "{}*") {
        panic("FileServer does not permit URL parameters.")
    }

    fs := http.StripPrefix(path, http.FileServer(root))

    if path != "/" && path[len(path)-1] != '/' {
        r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
        path += "/"
    }
    path += "*"

    r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fs.ServeHTTP(w, r)
    }))
}

홈 페이지를 로드할 수 있습니다(App.components.home모든 것이 동작하고 있는 것 같은 장소(CSS, 이미지, 번역, 서버에의 콜, 및 응답).그러나 404가 되는 다른 루트를 열거나 사용자를 로드하려고 하면 응답만 받습니다.404 page not found일반 텍스트(렌더해야 하는 vue not Found 컴포넌트가 아님)로 표시됩니다.

내가 뭘 잘못했는지, 어떻게 고칠지 생각나는 거 없어?


편집: 이것은 main.js 파일의 라우터 설정의 다른 부분입니다.

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes
})

new Vue({
  el: '#app',
  router,
  i18n,
  render: h => h(App)
})

틀릴 수도 있지만 방문하려는 경로는 서버(Go http 서버)에서 해결될 수 있습니다.

를 삭제해 볼 수 있습니다.mode: 'history'vue-time initialization에서 디폴트로hash모드(루트는 브라우저로 해결됩니다).이 링크를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/46144883/vue-router-in-production-serving-with-go

반응형