express+node处理跨域问题

  1. 最近写一个项目的时候,请求的是另一个服务器的接口,网上找遍了方法都没有用,最后用代理解决了,害!!


    image.png
  2. 两种方法,一种是本地起个nginx服务挂个代理,一种用http-proxy-middleware方式,原理都是一样的。

  3. nginx:

    • 本地起个nginx服务,然后在nginx.conf里面配置
      //前端没启服务这么写
        server {
           listen 8000; //代理端口
           server_name localhost;
           location / {
                 proxy_pass http://localhost:2000; // 前端资源
              }
           location ^~/api-proxy/ {
               proxy_pass http://localhost:3000/; //后端接口
        }
      }
      
      // 这是前端有服务的情况下,没有服务的情况下这么写
        server {
          listen 8000;
          root  /data/works/www/explore-frontend; #静态资源
          location ^~ /v3/ {    //这是匹配接口的配置,比如什么v3/xxx之类的
          proxy_pass http://localhost:8081;  #api 接口
         }
      }
      
    • 然后再命令行里面启动nginx就行了
  4. http-proxy-middleware

    • npm i http-proxy-middleware
    • 在express的app.js里面或者你自己命名的文件里面这么配置
       const { createProxyMiddleware } = require('http-proxy-middleware');
       const proxyOptions = {
          //换成你自己的请求接口路径
          target: 'http://dangerapi.1nongfu.com', // target host
          changeOrigin: true, // needed for virtual hosted sites
          ws: true, // proxy websockets
          pathRewrite: {
              //   '^/api/old-path': '/api/new-path', // rewrite path
          },
         router: {
             // when request.headers.host == 'dev.localhost:3000',
            // override target 'http://www.example.org' to 'http://localhost:8000'
           //   'dev.localhost:3000': 'http://localhost:8000',
        },
      };
      const exampleProxy = createProxyMiddleware(proxyOptions);
      app.use('/api', exampleProxy);//  /api换成你自己的匹配符就行了
      
      
  5. 在前端请求的url改成:

let tablesearchurl = '/api/poc/cc/order/0';

4.重启服务,请求成功

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。