【发布时间】: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
}
}
【问题讨论】: