前端部署nginx遇到的一些坑

2,157 阅读2分钟

项目背景:vue3项目,构建工具:vite 问题:

1.项目本地运行正常打包后上传到服务器,结果提示 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec

这是由于打包发布后找不到对应的资源导致的问题,解决办法: nginx配置:

location /hua_vue/ {
        alias html/hua_vue/;
        try_files $uri $uri/ /index.html;
        index index.html index.htm;	
}

最终的解决方法也很简单,将nginx转发的location和项目中vite配置文件中的 base 设置保持一致即可,这里我将目中vite配置文件中的 base设置为 /hua_vue,就不修改nginx配置了。问题完美解决。

export default defineConfig({
  base: "/hua_vue",
  ...
})

2.项目在线发布后,路由跳转时,会自动跳到nginx的根目录下,导致nginx报错。 这是由于项目的路由没有配置默认根路径与nginxlocation一致。解决办法: 修改router配置中的history的值为createWebHistory('/hua_vue/')。 nginx配置:

location /hua_vue/ {
        alias html/hua_vue/;
        try_files $uri $uri/ /index.html;
        index index.html index.htm;	
}

项目的路由文件配置

const router = createRouter({
  history: createWebHistory('/hua_vue/'),
  routes: [
    {
      path: '/',
      redirect: 'login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    ...appRoutes,
    REDIRECT_MAIN,
    NOT_FOUND_ROUTE,
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});

3.项目已部署,可以正常进入,但是在线上进行路由跳转后,刷新浏览器页面,报错: nginx报500

当前在vite.config.js中有如下配置

base: "/hua_vue"

router.js里面也配置了相应的路径:

history: createWebHistory('/hua_vue/')

nginx的部分配置如下:

location /hua_vue/ {
        alias html/hua_vue/;
        try_files $uri $uri/ /index.html;
        index index.html index.htm;	
}

但是刷页面后还是会报500, 查阅资料得知解决办法:修改nginx配置:

location /hua_vue/ {
        alias html/hua_vue/;
        try_files $uri $uri/ /hua_vue/index.html;
        index index.html index.htm;	
}

index.html前面加上'/hua'就好了,完美解决