跨域之反向代理


1.新建一個基於vue-cli3的一個項目,添加axios插件

vue create test
cd test
npm install axios
npm serve

2.編寫帶接口請求的頁面

 

 

 https://www.baidu.com/home/xman/data/tipspluslist是在百度頁面扒的一個get請求,

此時運行起來會看到頁面提示接口跨域

 

第一種:

此時使用vue.config.js文件(新建的vue項目沒有vue.config.js文件需要自己手動創建)設置proxy代理來解決跨域問題

vue.config.js:

module.exports = {
  // 修改啟動端口
  devServer: {
    proxy: {
      '/home': {
        target: 'https://www.baidu.com',
        changeOrigin: true
      }
    },
    disableHostCheck: true
  }
}

展示的vue界面

<template>
  <div class="hello">
    <h1 @click="useApi">點我請求接口</h1>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  methods: {
    useApi() {
      axios.get('/home/xman/data/tipspluslist').then((res) => {
        console.log(res)
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>

改完后需重新啟動項目

可以看到接口請求成功了

 

 第二種

設置nginx,使用nginx反向代理

1.打開nginx目錄下的conf目錄里面nginx.conf

2.修改nginx.conf的內容

首先我們知道前端請求鏈接是http://localhost:8081/,后端接口是https://www.baidu.com

然后配置nginx.conf

 server {
        listen 3003;
        server_name localhost;
        location / {
            proxy_pass http://localhost:8081;
        }
        location /home {
            proxy_pass https://www.baidu.com;
        }
    }
上面代碼的意思是將localhost:3003轉發為location:8081,也就是說現在訪問localhost:3003實際上是訪問location:5500,而訪問localhost:3003/home則是訪問https://www.baidu.com,並以home開頭的url

 

配置好后要重啟nginx(nginx -s reload)

 3.打開http://localhost:3003/可以看到頁面能成功打開,點擊請求接口也能成功請求了

 

注意:

vue.config.js 中配置的代理只是解決了開發環境的跨域,上線時需要配置 nginx 代理

 

nginx相關配置詳解https://www.cnblogs.com/myitnews/p/11544707.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM