vue proxy代理 + nginx 處理跨域

前言: 身爲一名前端菜鳥,之前一直未關注後端對於跨域的配置,這不,終於又踩到坑了,由於nginx未配置代理轉發,所以前端的處理一直都是針對開發環境和生產環境做處理

// 錯誤 的代理配置,同樣啓用proxy代理,並在axios配置文件中根據開發環境配置請求,這樣在開發環境中可以正常請求,但是在生產環境中由於直接請求,瀏覽器會進行預請求OPTIONS
http預請求options,這是瀏覽器對複雜跨域請求的一種處理方式,在真正發送請求之前,會先進行一次預請求,就是我們剛剛說到的參數爲OPTIONS的第一次請求,他的作用是用於試探性的服務器響應是否正確,即是否能接受真正的請求,如果在options請求之後獲取到的響應是拒絕性質的,例如500等http狀態,那麼它就會停止第二次的真正請求的訪問

const baseUrlHash = {
  production: 'http://test.admin.xxx.com',
  development: '/api'
}
const BASE_URL = baseUrlHash[process.env.NODE_ENV]
axios.defaults.baseURL = BASE_URL

正確 的代理配置
vue.config.js 配置proxy代理,不需要做別的配置,只需nginx轉發後端接口地址

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://test.admin.xxx.com',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/http': {
        target: 'http://test.xxx.com',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/http': ''
        }
      }
    }
  }
}

axios 配置文件,根據需求是否添加默認前綴

axios.defaults.baseURL = '/api'

/etc/nginx/conf.d project.conf 配置nginx —重點

server {
    listen 80;
    server_name  pcadmin.xxx.com;
    location / {
        try_files $uri $uri/ /index.html;
        #proxy_pass http://localhost:8089;
        // 項目地址
        root /home/xfw/xfw-admin-html/dist;
        index  index.html index.htm;
    }
    // 轉發後端接口地址---重點
    location ^~ /api/ {
        proxy_pass http://test.admin.xxx.com/;
    }
    location ^~ /http/ {
        proxy_pass http://test.xxx.com/;
    }
}

nginx未配置轉發後端接口地址bug:
We’re sorry but XX doesn’t work properly without JavaScript enabled

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