【问题标题】:calling server by proxy doesn't pass parameters通过代理调用服务器不传递参数
【发布时间】:2023-02-05 05:15:01
【问题描述】:

我有一个 React UI 应用程序和一个 .NET API 服务器。

React 应用程序在本地运行:http://localhost:8082/myapp

API 应用程序在 IIS 上本地运行:http://foo.local.bar.com/myappapi

我想让他们交流。由于它们在不同的本地域上运行,我需要一个代理来避免 CORS 问题。在我的 React 应用程序中,我将此代码放在我的 config.development.js 文件中:

 devServer: {
    logLevel: 'debug',
    proxy: {
      '/myappapi/api/*': {
        target: 'http://foo.local.bar.com/',
        headers: {
          Cookie: ".MyCookie=12345"
        },
        logLevel: 'debug',
        secure: false,
        changeOrigin: true,
        withCredentials: true
      }
    },
  },

好吧,它与 GET 方法配合得很好,我确实从 API 服务器获取数据到 UI。

问题是我想传递数据的 POST/PUT/DELETE 方法 - 它不起作用,一段时间后我收到网关错误。我知道我传递了正确的对象,因为它在生产环境中运行良好,问题仅出现在代理模式(本地)上。

到目前为止我发现的事情:

  • 正如我所说,GET 方法效果很好(数据在 URL 中,而不是在正文中)所以代理被正确定义。
  • 没有参数的 POST 方法也能正常工作。
  • 带参数的 POST 方法在没有代理的情况下工作正常(邮递员到 foo.local.bar 中的原始 URL,或在生产模式下)。

这是服务器中的代码:

    [Route("api/mycontroller/v1")]
    [ApiController]
    public class MyController : ControllerBase
    {
        private readonly ILogger logger;
        private readonly IMyService myService;

        /// Constructor
        public MyController (IMyService myService) // When I send the POST method, I hit the breakpoint here
        {
            this.myService = myService; 
            logger = LogManager.GetCurrentClassLogger();
        }

        [HttpPost]
        [Route("PostSomething1")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult> AddAsync(MyObjRequest myRequest)
        {
            // I never get here on proxy mode
        }

        [HttpPost]
        [Route("PostSomething2")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult> AddAsync2()
        {
            // This one works fine - but I can't get data from UI so it doesn't help me much
        }
}

【问题讨论】:

    标签: .net post proxy


    【解决方案1】:

    好吧,在挖掘代码之后,我发现我们的系统正在使用 HPM (httpProxyMiddleware),它在早期版本中有一个错误(在谷歌中搜索“fixRequestBody”)。由于它在我们的内部包中,我无法升级包,所以我将解决方案从 GitHub 复制到我的项目并将其匹配到 JS 而不是 TS。

    devServer: {
        logLevel: 'debug',
        proxy: {
          '/myappapi/api/*': {
            target: 'http://foo.local.bar.com/',
            headers: {
              Cookie: ".MyCookie=12345"
            },
            logLevel: 'debug',
            secure: false,
            changeOrigin: true,
            withCredentials: true,
            onProxyReq: fixRequestBody, // Here is the solution!!!
          }
        },
    

    功能是 -

    const queryString = require('queryString');
    
    function fixRequestBody(proxyReq,req){
      const requestBody = req?.body;
      if (!requestBody || !Object.keys(requestBody).length) {
        return;
      }
    
      const contentType = proxyReq.getHeader('Content-Type');
      const writeBody = (bodyData) => {
        // deepcode ignore ContentLengthInCode: bodyParser fix
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        proxyReq.write(bodyData);
      };
    
      if (contentType && contentType.includes('application/json')) {
        writeBody(JSON.stringify(requestBody));
      }
    
      if (contentType === 'application/x-www-form-urlencoded') {
        writeBody(queryString.stringify(requestBody));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      相关资源
      最近更新 更多