通过代理解决跨域问题
1.创建项目
先构建一个webpack构建一个vue项目
$ vue init webpack [项目名]
构建完成了进入项目 并安装 Axios 使用axios进行数据交互
$ npm install axios
引入axios
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
Vue.prototype.$axios = Axios
2.配置代理跨域
找到 config\index.js 配置代理
这里使用豆瓣电影top250接口 https://api.douban.com/v2/movie/top250 测试跨域
// config\index.js
proxyTable: {
'/api': {
target: 'https://api.douban.com', //设置你调用的接口域名和端口号
changeOrigin: true, //设置跨域
pathRewrite: {
'^/api': '/' // 用'/api'代替url地址中'https://api.douban.com'部分
}
}
},
引入跨域接口
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
Vue.prototype.$axios = Axios
Vue.prototype.HOST = '/api' //通过prototype 添加Vue属性 HOST
3.测试代理接口
HelloWorld.vue
// HelloWorld.vue
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
created () {
let url = this.HOST + '/v2/movie/top250'
this.$axios.get(url).then(res => {
console.log(res)
}).then(error => {
if (error) {
console.log(error)
}
})
}
}
最终可以在console.log打印出跨域接口数据
假如端口为:8080
那么接口代理地址为 http://localhost:8080/api/v2/movie/top250