跨域代理

215 阅读1分钟

一、proxy 代理

假如现在我们本地访问的域名是 http://localhost:3000, 但是我现在调用的是百度页面中的一个接口,该接口地址是:news.baidu.com/widget?ajax…

webpack配置

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://news.baidu.com', // 目标接口的域名
        // secure: true,  // https 的时候 使用该参数
        changeOrigin: true,  // 是否跨域
        pathRewrite: {
          '^/api' : ''  // 重写路径
        }
      }
    }
  }
}

请求代码

import axios from 'axios';

axios.get('/api/widget?ajax=json&id=ad').then(res => {
  console.log(res);
});
  1. 首先是百度的接口地址是这样的:news.baidu.com/widget?ajax…;
  2. proxy 的配置项 '/api' 和 target: 'news.baidu.com' 的含义是,匹配请求中 /api 含有这样的域名 重定向 到 'news.baidu.com'来。因此我在接口地址上 添加了前缀 '/api', 如: axios.get('/api/widget?ajax=json&id=ad'); 因此会自动补充前缀,也就是说,url: '/api/widget?ajax=json&id=ad' 等价
    于 url: 'news.baidu.com/api/widget?…'.
  3. changeOrigin: true/false 还参数值是一个布尔值,含义是 是否需要跨域。
  4. secure: true, 如果是https请求就需要改参数配置,需要ssl证书吧。
  5. pathRewrite: {'^/api' : ''}的含义是重写url地址,把url的地址里面含有 '/api' 这样的 替换成 '', 因此接口地址就变成了 news.baidu.com/widget?ajax…

二、nginx 代理

nginx配置

 location /robot {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }
   proxy_pass http://news.baidu.com/robot; 
}

页面请求

axios({
  method: 'post',
  url: '/robot/send?access_token=xxx',
  headers: {
    'Access-Control-Allow-Origin': '*',
  },
  data: data,
})