在dev模式下使用react

时间:2016-07-12 13:44:48

标签: c# node.js

我的服务器端是C# mvc项目。

我们尝试对客户端实施反应。

我正在node-js使用npm,使用express服务器和hot-reloading,因此当我编译客户端代码时,它会在http://localhost:3000上运行。

现在我想添加一些服务器端调用。 为此,我使用iis express运行我的c#代码,该代码也在另一个端口的localhost上打开。 现在的问题是,当端口:3000上的客户端代码正在对iis express进行ajax调用时,也会在localhost上收到"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>

编辑 - 解决方案

当您将帖子发送到其他域时,首先客户端发送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();
    }
}

1 个答案:

答案 0 :(得分:0)

在你的情况下,&#34; React&#34;应用程序的一部分归结为静态资源:引导应用程序的初始html文件,带有React组件及其依赖项的.js软件包,以及任何其他 static < / strong>从初始html文件引用的.css文件,图像等资产(通过脚本标记,链接标记等)。

您的应用的C#部分只关注动态请求,这相当于api / ajax调用以获取React将用于在浏览器中呈现应用的数据。

我将假设您正在使用Webpack和Webpack Dev Server。开发时最简单的方法是让您的Webpack Dev Server只代理任何api / ajax请求到运行IISExpress的端口。这是Webpack.config.js文件中的一个简单设置(请参阅https://webpack.github.io/docs/webpack-dev-server.html#proxy)。您使用Webpack在构建期间创建捆绑包,然后它们仅在运行时从Web服务器充当静态资源。

在生产环境中,IIS提供所有内容(包括静态和动态请求)以及可能授权访问在提供React应用程序之前引导您的React应用程序的html资源,因此不涉及Express服务器。