什么是跨域?
一句话:你可以理解成,别人为了防止你直接访问api,攻击他们的服务器做的保护伞。
那么我们怎么解决访问题,去访问别人的数据呢?
使用《vue-反向代理》
1.下载axios安装https://github.com/axios/axios,我这里用的yarn,yarn真的超级好用
$ yarn add axios
npm 的用户可以用如下
$ npm install axios
不同的终端不同的代码大家可以直接在github中搜索axios查看安装代码

我们使用下面的代码直接复制到vscode编译器中
get
axios.get(‘你的API去掉com之前的内容').then(function(response)
{// handle successconsole.log(response);})//打印返回结果
.catch(function(error){
// handle errorconsole.log(error);}) //捕获异常
.then(function(){
// always executed}); //接下来执行
举个例子:axios。你的完整网站是:http://m.xxxxxxxxxxxxxxxxxxxxx.com/ /ajax/movieOnInfoList?token=
get里面放入:/ajax/movieOnInfoList?token=
post
axios.post('你的API去掉com之前的内容',{firstName:'Fred',lastName:'Flintstone'})
.then(function(response){console.log(response);})
.catch(function(error){console.log(error);});
vue中请求
// vue中导入import
<script>
import axios from 'axios'
export default {
mounted() {
axios.get("/ajax/movieOnInfoList?token=")
.then(function (response) {
// handle success
console.log(response);
})
</script>
最后创建一个vue.config文件,位置要与package。json平级,我们在vuecli的官方文档中就可以查看到相关的说明,我们直接把代码复制过来

module.exports = {
devServer: {
proxy: {
'/ajax': { //这里你要设置在什么字符串中拦截代理,白话文网站最好设置com结尾后面的字符串
target: 'http://m.xxxxxxxxxxxxxxxxxxxxx.com', //里面设置为网站地址
// ws: true,
changeOrigin: true
},
// '^/foo': {
// target: '<other_url>'
// }
}
}
}
最后我们重启一下服务器就可以查看到结果
你可以使用
npm run serve
或者用
yarn serve