vue-cli axios跨域问题

首先输入命令vue init webpack + 项目名称 构建初始化vue-cli项目 

npm i axios  在main.js文件中配置

import axios from 'axios'
Vue. prototype. $axios = axios

然后  在config index.js文件中配置 以 豆瓣的接口为例

assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api' : { //
target: 'http://api.douban.com/',
changeOrigin: true,
pathRewrite: {
'^/api' : ''
}
}
// 其中 '/api'
// 为匹配项, target 为被请求的地址

// 因为在 ajax 的 url 中加了前缀 '/api',
// 而原本的接口是没有这个前缀的

// 所以需要通过 pathRewrite 来重写地址, 将前缀 '/api'
// 转为 '/'

// 如果本身的接口地址就有 '/api'
// 这种通用前缀, 就可以把 pathRewrite 删掉
},

然后在需要跨域的请求中

getky() {
this. $axios. get( '/api/v2/movie/top250'). then( res => {
console. log( res)
})
}

这样就可以进行跨域了


猜你喜欢

转载自blog.csdn.net/hailangtuteng/article/details/80288976