Axiso解决跨域访问
问题:
在项目中需要需要讲本地项目去请求一个URL接口获取数据 例如:
本地请求地址:http://127.0.0.1:19323/site/info.json 请求Url地址:http://www.v2ex.com/api/site/info.json
那么如何让本地的请求转换乘正确的请求地址URL呢?
首先请检查下你的 Vue 版本,Vue2 和 Vue3 跨域方式不同:
$ vue -V 2.X or 3.X
一、Vue2 版本
这里以访问 Ve2x 的一个公告API为例,直接访问如下:
this.$axios.get("https://www.v2ex.com/api/site/info.json")
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})
当我们运行程序后,控制台报错如下:
可以看到浏览器拦截了我们的请求,因为我们跨域了,下面解决跨域问题。
Step1:配置BaseUrl
首先在main.js中,配置下我们访问的Url前缀:
import Vue from 'vue'
import App from './App'
import Axios from 'axios'
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api'
Axios.defaults.headers.post['Content-Type'] = 'application/json';
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})
关键代码是:Axios.defaults.baseURL = '/api',这样每次发送请求都会带一个/api的前缀
Step2:配置代理
修改config文件夹下的index.js文件,在proxyTable中加上如下代码:
'/api':{
    target: "https://www.v2ex.com/api",
    changeOrigin:true,
    pathRewrite:{
        '^/api':''
    }
}

Step3:修改请求Url
修改刚刚的axios请求,把url修改如下:
this.$axios.get("/site/info.json")
.then(res=>{
	console.log(res)
})
.catch(err=>{
	console.log(err)
})
Step4:重启服务
重启服务后,此时已经能够访问了:
原理:
因为我们给url加上了前缀 /api,我们访问 http://127.0.0.1:19323/site/info.json 就当于访问了:http://127.0.0.1:19323/api/site/info.json。(假设本地访问端口号为 19323)
又因为在 index.js 中的 proxyTable 中拦截了 /api ,并把 /api 及其前面的所有替换成了 target 中的内容,因此实际访问 Url 是https://www.v2ex.com/api/site/info.json。
二、Vue3 版本
升级到 Vue3 后,会发现 Vue2 中存放配置的 config 文件夹没有了,大家不要慌张。可以在 package.json 文件的同级目录下创建 vue.config.js 文件。给出该文件的基础配置:
module.exports = { outputDir: 'dist', //build输出目录 assetsDir: 'assets', //静态资源目录(js, css, img) lintOnSave: false, //是否开启eslint devServer: { open: true, //是否自动弹出浏览器页面 host: "localhost", port: '8081', https: false, //是否使用https协议 hotOnly: false, //是否开启热更新 proxy: null, } }

Vue3 解决跨域,内容只有第二步配置代理 和 Vue2 不同,其他的一致。
Step2:配置代理
修改 vue.config.js 中 devServer 子节点内容,添加一个 proxy:
devServer: {
    open: true, //是否自动弹出浏览器页面
    host: "localhost", 
    port: '8081',
    https: false,
    hotOnly: false, 
    proxy: {
        '/api': {
            target: 'https://www.v2ex.com/api', //API服务器的地址
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
}
当然还有一种方式,将本地的Localhost的host地址直接转请求url
改编转载:https://blog.csdn.net/yuanlaijike/article/details/80522621
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号