My server side is a C#
mvc project.
We try to implement react to the client side.
I am using node-js
with npm
, using express
server and hot-reloading
, So when i compile my client-side code it runs on http://localhost:3000.
Now i want to add some server side calls.
To do that I run my c#
code using iis express which also opens on localhost in another port.
Now the problem is that when the client code on port:3000 is making ajax calls to the iis express which is also on localhost i receive the "Response for preflight is invalid (redirect)"
error, which is because of the same domain policy.
So what am i doing wrong, how are you suppose to work on dev mode when your server and client are seperated?
I tried to add to my 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>
Edit - solution
When you send a post to a different domain, so first the client sends an OPTIONS
request. So the solution is actually to add this code:
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();
}
}