当前位置: 首页 > 后端技术 > Node.js

解决vue-axios和vue-resource的跨域问题

时间:2023-04-03 23:15:03 Node.js

个人博客同步文章https://mr-houzi.com/2018/02/...最近在学习vue,vue里面没有ajax,但使用vue-resource和vue-axios进行数据通信。Vue2.0之后,官方推荐使用vue-axios。问题是在使用vue-axios的post请求时存在跨域问题。错误如下:Responsetopreflightrequestdoesn'tpassaccesscontrolcheck:No'Access-Control-Allow-Origin'headerispresentontherequestedresource。因此不允许访问源“http://localhost:8081”。响应有HTTP状态代码404。解决步骤在config/index.js中添加proxyTable代理方法proxyTable:{'/api':{target:'http://api.com/',changeOrigin:true,pathRewrite:{'^/api':'/vue'}}}target为目标地址pathRewrite为重定向地址(一般为空)完整地址为http://api.com/vue组件中请求如下:created(){axios.post('/api/Login',{data:'data'}).then(function(response){console.log(response);}).catch(function(error){console.log(error);});}结果是向http://api.com/vue/Login地址发送请求。在专门声明中设置proxyTable代理方法后,需要将main.js中设置的baseUrl注释掉,否则proxyTable会失效,还是会出现跨域错误。(这个很重要,我自己也困惑了很久)//main.js//axios.defaults.baseURL='http://api.com/';//设置proxyTable代理解决跨域问题并注释掉baseURLaxios.defaults。headers.common['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';PS:vue-resource解决了vue-resource的跨域问题-proxyTable代理方法的设置和axios一样,但是特殊声明里面的内容不是必须的。