我的服务器端是一个C#
mvc项目。
我们尝试在客户端实现react。
我使用node-js
和npm
,使用express
服务器和hot-reloading
,所以当我编译我的客户端代码时,它在http://localhost:3000上运行。
现在我想添加一些服务器端调用。为此,我使用iis express运行我的c#
代码,它也在另一个端口的本地主机上打开。现在的问题是,当端口:3000上的客户端代码对同样在本地主机上的iis express进行ajax调用时,我收到了"Response for preflight is invalid (redirect)"
错误,这是由于相同的域策略造成的。
那么,我做错了什么?当你的服务器和客户端分离时,你应该如何在开发模式下工作?
我尝试添加到我的ASP.NET
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
编辑-解决方案
因此,当您将post发送到其他域时,客户端首先会发送一个OPTIONS
请求。因此,解决方案实际上是添加以下代码:
protected void Application_BeginRequest(object sender, EventArgs e)
{
EnableCrossOriginRequestsFromLocalhost(HttpContext.Current.Request);
}
private void EnableCrossOriginRequestsFromLocalhost(HttpRequest request)
{
if (!HttpContext.Current.Request.IsLocal) return;
if (request.UrlReferrer == null) return; //can't set Access-Control-Allow-Origin header reliably without a referrer so just return. Referrer should always be set when being called from an app under development because the app under development's URL will be sent as the referrer automatically.
var response = HttpContext.Current.Response;
response.AddHeader("Access-Control-Allow-Origin", request.UrlReferrer.GetLeftPart(UriPartial.Authority));
response.AddHeader("Access-Control-Allow-Credentials", "true");
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.AddHeader("Access-Control-Max-Age", "1728000");
response.End();
}
}
发布于 2016-12-25 16:37:06
在您的例子中,应用程序的" React“部分都归结为静态资源:引导应用程序的初始html文件、包含React组件及其依赖项的.js包,以及从初始html文件(通过脚本标签、链接标签等)引用的任何其他静态资源,如.css文件、图像。
然后,应用程序的C#部分只关注动态请求,这相当于获取数据的应用程序接口/ajax调用,React将使用这些数据在浏览器中呈现应用程序。
我将假设您使用的是Webpack和Webpack开发服务器。开发时最简单的方法是让您的Webpack开发服务器将任何api/ajax请求代理到运行IISExpress的端口。这是Webpack.config.js文件(请参见https://webpack.github.io/docs/webpack-dev-server.html#proxy)中的一个简单设置。您可以在构建时使用Webpack创建包,然后在运行时从web服务器将它们作为静态资源提供。
在生产环境中,IIS提供所有服务(静态和动态请求),可能还会在提供React应用程序之前授权访问引导React应用程序的html资源,因此不涉及Express服务器。
https://stackoverflow.com/questions/38330698
复制相似问题