使用axios时遇到问题
已拦截跨源请求:同源策略禁止读取位于
在本地调试访问远程服务器,就有跨域问题,下面以调用豆瓣接口为例:
解决办法
3.x 版本对整个项目的构建都有很大的改动,没有原先的config文件夹,没有dev.env.js和prod.dev.js,要自己在根目录建vue.config去配置
1 创建vue.config.js

module.exports = { devServer: { open: true, host: 'localhost', port: 8080, https: false, //以上的ip和端口是我们本机的;下面为需要跨域的 proxy: { //配置跨域 '/home': { //这里后台的地址模拟的;应该填写你们真实的后台接口 target: 'http://123.207.32.32:8000/', ws: true, changOrigin: true, //允许跨域 pathRewrite: { '^/home': '' //请求的时候使用这个api就可以 } }, '/apis': { target: 'https://movie.douban.com/', // target host ws: true, // proxy websockets changeOrigin: true, // needed for virtual hosted sites pathRewrite: { '^/apis': '' // rewrite path } }, } } }
2 srcmain.js
import axios from 'axios'
axios.get('http://123.207.32.32:8000/home/multidata').then(res=>{ console.log(res); }) axios.get('/apis/ithil_j/activity/movie_annual2017').then(res => { console.log(res.data) }, res => { console.info('调用失败'); })
成功访问
附:vue2.0 解决办法:https://segmentfault.com/a/1190000014396546