天天看点

vue/react项目中使用proxy代理处理跨域问题

vue/react项目中使用proxy代理处理跨域问题

最近在项目更新迭代中遇到需要设置代理来访问服务器的问题,跟大家分享下!(刚好是两个框架的项目并行开发…)

proxy:本地的网站请求的数据会通过我们的服务器进行代理,由服务器发送真实的数据请求到目标数据后台 ! 浏览器有同源策略,但是服务器没有.

1.vue项目中一般在config\index.js下dev或者vue.comfig.js的proxyTable配置,

react项目一般在webpack.config.js中devServer里来配置proxy。

devServer.proxy 可以是一个指向开发环境 API 服务器的字符串

```c
//	默认服务器会将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000上
module.exports = {
  devServer: {
    proxy: '代理地址'
  }
}
           

2.(配置proxy)代码示例

proxy: {
        '/mobile': { 
        // proxy的key表示匹配以这个字段开头的请求
        target: "代理地址", 
        // 配置需要跨域的IP(域名)地址/访问目标地址
        secure: false,  // 如果是https此处改为true
       	ws: true,  // 如果要代理 websockets,才配置这个参数
        changeOrigin: true, // 是否跨域,true为允许跨域
        pathRewrite: { '^/mobile': '/mobile' },
        // 代表重写,前边的是匹配规则,后边是重写本地发起的路径,
        // 如果target中包含了key值/mobile,则{ '^/mobile': '/' },。
      }
},
           

proxy里面可写多个key值来匹配更多的地址

proxy: {
      '/mobile': {
        target: '代理地址',
        secure: false,
        changeOrigin: true,
        pathRewrite: { '^/mobile': '/mobile' },
      },
      "/api": {
        target: "代理地址",
        changeOrigin: true,
        pathRewrite: { "^/api": "/" },
      },
      '/': {
  			target: '代理地址',
  			changeOrigin: true,
 			pathRewrite: {},
	  },
    },
           

一般这样代理就配置好了,记得重启项目!如设置了多个代理,有的未生效,可以百度下 proxy的匹配规则。

解决跨域方法不止一种,选择适合的即可

------	希望能够帮助大家,感谢大家围观阅读	------