vue.js使用http-proxy-middleware解决跨域请求问题

JavaScript02

vue.js使用http-proxy-middleware解决跨域请求问题,第1张

最近在使用vue-cli搭建项目的过程中,遇到了跨域请求数据的问题,这里贴出我的解决方法,希望对大家有所帮助。

什么是跨域请求:

如果在A网站中,我们希望使用Ajax来获得B网站中的特定内容,如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题。由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

这里,数据请求用的是vue-resource(目前vue官方是推荐使用axios),安装插件:

npm install--save-devvue-resource

1

在main.js中引入插件:

importVueResourcefrom'vue-resource'

Vue.use(VueResource)

这里,解决跨域使用的是http-proxy-middleware来进行接口代理,安装方法同上:

npm install--save-devhttp-proxy-middleware

下面开始谈正事,举个栗子:

本地项目地址是:localhost:8080,现在我们要访问  http://m.maizuo.com/v4/api/film/comming-soon  和  http://m.maizuo.com/v4/api/billboard/home  这两个线上地址:

首先,设置build/dev-server.js:

varproxyMiddleware =require('http-proxy-middleware')

varserver = express()

server.middleware = [        proxyMiddleware(['/film/coming-soon'], {target:'http://m.maizuo.com/v4/api', changeOrigin:true}),        proxyMiddleware(['/billboard/home'], {target:'http://m.maizuo.com/v4/api', changeOrigin:true})]

server.use(server.middleware)

注意,当要访问多个线上地址时,公共的地址部分写在target属性值里面,比如这里的  http://m.maizuo.com/v4/api  ,然后[ ]里边写地址的不同部分。

然后,修改config/index.js :

dev:{env:require('./dev.env'),    port:8080,    proxyTable: {'/api': {        target:'http://m.maizuo.com/v4/api',        changeOrigin: true,        pathRewrite: {'^/api':''}      }    }  }

这里的target同上面的一样,然后’/api’和’^/api’代表的就是这个根目录地址;

然后,在页面中具体的调用为:

this.$http.get('api/billboard/home').then((response) =>{

})

这里,url的值为api + [ ] 中的部分

然后,我们就解决了vue中的跨域问题

这里,贴一下http-proxy-middleware插件的github地址,看更多用法 :

https://github.com/chimurai/http-proxy-mid

vue跨域解决方法

使用axios请求

第一步骤

在vue.config.js 文件中 module.exports = { } 中添加

devServer: {

proxy: {

'/profile': { //指定 路径 要 跨域请求地址

// 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题

// 将/api开头的url转发到target上。

target: ' https://sso.www.eee.cn/profile',// 跨域请求地址

changeOrigin: true, //虚拟的站点需要更管origin

ws: true, // 代理websockets

secure: true, // 如果是https接口,需要配置这个参数

pathRewrite: {

// 顾名思义,将/api重写为 / 此时url变为 http://192.168.101.110:8888/ 而不是 http://192.168.101.110:8888/api

'^/profile': ''

}

}

}

第二步骤

在封装axios请求中设置

const service = axios.create({

baseURL: '/profile',//定义要跨域的接口路径

withCredentials: true,//是否支持跨域

timeout: 500000, // request timeout

headers: {

'Cache-Control': 'no-cache',

'Content-Type': 'application/x-www-form-urlencoded'

}

})