javaLuo / react-admin

动态菜单配置、权限精确到按钮、通用模块;标准后台管理系统解决方案
https://isluo.com/work/admin/
Mulan Permissive Software License, Version 2
517 stars 152 forks source link

关于跨域问题 #6

Closed yiyu-liao closed 4 years ago

yiyu-liao commented 4 years ago

hello,感谢开源~ 请问如果要连接本地其他端口node后台服务需要怎样设置跨域? 我尝试在webpack.dev.config.js中加上如下代码,貌似不行

devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:9527/api/admin",
        changeOrigin: true,
        pathRewrite: {'^/api' : ''}
      }
    }
  },
javaLuo commented 4 years ago

试试在server.js中设置:

const { createProxyMiddleware } = require("http-proxy-middleware");

app.use(
  "/api",
  createProxyMiddleware({
    target: "http://localhost:9527/api/admin",
    changeOrigin: true,
    ws: false,
    pathRewrite: {
      "^/api": "/"
    }
  })
);

我稍后把proxy的配置更新到代码里

yiyu-liao commented 4 years ago

image

javaLuo commented 4 years ago

使用最新版本的http-proxy-middleware

换个名字吧,我代码里面mock占用了/api,

app.use(
  "/proxy",
  createProxyMiddleware({
    target: "https://example.com", // 目标域名
    changeOrigin: true,
    ws: false,
    pathRewrite: {
      "^/proxy": "/",
    },
  })
);
javaLuo commented 4 years ago

我试了一下,可以成功代理 实在不行你把server.js中的mock配置注释掉

下面这几行是mock配置,我的mock占用了/api

const mock = require("./mock/app-data"); // mock模拟数据,模拟后台业务

/** 监听POST请求,返回MOCK模拟数据 **/
app.post(/\/api.*/, (req, res, next) => {
  const result = mock.mockApi({ url: req.originalUrl, body: req.body });
  res.send(result);
});
app.get(/\/api.*/, (req, res, next) => {
  const result = mock.mockApi({ url: req.originalUrl, body: req.body });
  res.send(result);
});
yiyu-liao commented 4 years ago

找到问题所在了,算是一个小坑。你在server.js中用了body-parser,而我的node服务用了koa-body,两个同时存在的时候,会导致post请求挂起。我的解决方法是在server.js屏蔽如下两段代码:

// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.json());

或者createProxyMiddleware增加onProxyReq属性:

app.use(
  "/api",
  createProxyMiddleware({
    target: "http://localhost:9527", // 目标域名
    changeOrigin: true,
    ws: false,
    onProxyReq: (proxyReq, req, res, options) => {
      if (req.body) {
        const bodyData = JSON.stringify(req.body);
        // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        proxyReq.write(bodyData);
      }
    }
  })
);

官方issue: https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-249430255

javaLuo commented 4 years ago

厉害了我的哥 nice

yiyu-liao commented 4 years ago

向大佬学习~