使用koa、Nginx處理vue項目的history模式

使用koa處理vue項目的history模式

在vue項目的路由中默認是hash模式,又叫前端路由,根據瀏覽器url地址欄中的變化,使用onhashchange事件監聽做出相應的操作,不會向服務器發送請求。但是若採用了history模式,就大大不同了,history不怕前進不怕後退就怕刷新,history模式是由瀏覽器提供的history api來處理。而且將vue項目(非ssr)打包後的靜態資源部署到不同的服務器中,服務器的配置也不同。這裏我首先使用了nodejs提供的koa網絡服務框架來解決這一問題。

vue打包

我這裏使用的是vue-cli 4.x版本,這裏要注意,若你使用的vue-cli在3.0及其以上,在vue.config.js配置文件中basePath配置項要使用publicPath來代替。在生產環境下要將publicPath設置爲/根路徑,爲了我們的資源重定向。然後將路由模式設置爲history模式。

// router.js
const router = new VueRouter({
  mode: 'history',
  routes
})

koa服務

這裏面的主角是koa2-connect-history-api-fallback這個中間件。這個中間件是基於connect-history-api-fallback實現,新增了白名單,不是讓所有404都指向index.html。
傳送門:
koa2-connect-history-api-fallback
connect-history-api-fallback
依賴:

yarn add koa koa-router koa-static koa2-connect-history-api-fallback

啓動文件:

const path = require('path');
const Koa = require('koa');
const Router = require('koa-router');
const static = require('koa-static');
const { historyApiFallback } = require('koa2-connect-history-api-fallback');

const app = new Koa();
const router = new Router();

app
    // koa2-connect-history-api-fallback中間件一定要放在靜態資源服務中間件前面加載
    .use(historyApiFallback({
        index: '/index.html'
    }))
    // 配置靜態資源服務中間件,指定域名根目錄的映射
    .use(static(path.join( __dirname, '/public')))

// 配置路由
router
    .get('/', async ctx => {
        ctx.render('index');
    })
    // 其他路由匹配規則....

// 應用路由
app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000);

部署

將打包後的vue項目放在服務端的靜態資源public(案例中的位置)文件夾中,啓動服務文件就可以了。
服務端目錄結構:

|——node_modules/
|——public/
|———assets/
|———favicon.ico
|———index.html
|——server.js
|——yarn.lock
|——package.json

Nginx部署Vue項目,history模式配置

Nginx靜態部署主要解決兩個痛點

  1. 刷新404,我們可以用重定向解決
  2. 資源請求跨域處理,可以配置請求頭。
server
{
    listen 80;
	listen 443 ssl http2;
    server_name [你的域名];
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/[你站點文件夾];
    
	# 圖標404請求根路徑
    location ~ ^/favicon\.ico$ {
      root /www/wwwroot/[你站點文件夾];
    }
    
    # 防止請求跨域
    location / {
      index index.html index.htm;
      try_files $uri $uri/ @fallback;
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Credentials' 'true';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
      proxy_set_header   Host             $host;
      proxy_set_header   X-Real-IP        $remote_addr;
      proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Proto  $scheme;
    }
    
    # history刷新404重定向到index.html
    location @fallback {
      rewrite ^.*$ /index.html break;
    }
    ....
}

文章推薦

瀏覽器中hash和history兩種模式的區別

其他服務端還未測試,推薦一篇文章,有興趣的小夥伴可以測試一下。
vue路由的兩種模式配置以及history模式下面後端如何配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章