Vue項目跨域的解決辦法

 

                                            Vue項目中的跨域問題

 

一般我們的前端Vue項目中都會涉及到跨域的問題,在項目中訪問web域名獲取數據時無法正常獲取,瀏覽器控制檯會類似出現

跨域一般分兩種情形:

 

  • 開發環境跨域

項目使用的是axios請求網絡,將baseUrl修改爲/api (這裏是使用webpack提供的代理功能將/api代理成目標接口host)

axios.defaults.baseURL = '/api';

進入config/index.js裏,在dev下增加proxyTable配置,可以匹配到/api,將其代理成目標接口host

dev: {
 
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'xxxxxxxxxxxxx',//目標接口域名
        changeOrigin: true,//是否跨域
        pathRewrite: {
          '^/api': ''//重寫接口,後面可以使用重寫的新路徑,一般不做更改
        }
      }
    }
}

此時已經解決了dev下的跨域問題。

進入package.json,在dev字段下增加 " --host 0.0.0.0 ",這樣可以真機通過ip地址訪問項目,進行調試

"scripts": {
    "dev": "webpack-dev-server --host 0.0.0.0 --inline --progress --config                                                 build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js"
  }

 


  • 生產環境跨域

同樣將axios的baseURL修改爲 /api, (生產環境下是使用nginx反向代理,將/api 代理成目標接口host).

axios.defaults.baseURL = '/api';

進入config/index.js裏,在build下修改項目路徑,將assetsPublicPath字段的 '/' 修改爲 '/your_project_name' (名稱和項目名稱目錄一致)

build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
 
    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/your_project_name',
    ...
}

build項目,將生成的dist文件夾裏的文件,複製到tomcat服務器的webapps的項目目錄下,我們這裏結合nginx使用反向代理來解決。進入nginx/conf目錄,新建文件夾your_project_name,以及our_project_name.conf文件

 

編輯your_project_name.conf配置文件,配置反向代理.

server {
        listen       83; #監聽83端口,可以改成其他端口
        server_name  localhost; # 當前服務的域名(nginx所在服務器域名)
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            proxy_pass http://localhost:8080;#代理項目部署的地址(這裏項目部署在了當前服務器tomcat上,端口8080)
            proxy_redirect default;
        }
 
		location /api { #添加訪問目錄爲/api的代理配置,使以“/api”開頭的地址都轉到“http://192.168.1.111:8080”上
			rewrite  ^/api/(.*)$ /$1 break;
			proxy_pass   http://192.168.1.111:8080;
        }
}

接着進入nginx/conf/nginx.conf配置文件,導入上面的your_project_name.conf配置.

http {
    ...
 
    include myconfig/*.conf;
    ...
}

此時已可以通過nginx代理訪問tomcat下的項目,並且解決了跨域問題.

 

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