How to overcome the CORS issue in ReactJS
The ideal way would be to add CORS support to your server.
You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.
There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client.
The thing that will do the trick us the proxy_pass
directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass
or redirect your request to your actual server.
CORS problems usually occur because of change in the website domain.
When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.
Consider this example.
Your server is my-server.com
and your client is my-client.com
Configure nginx as follows:
// nginx.conf
upstream server {
server my-server.com;
}
upstream client {
server my-client.com;
}
server {
listen 80;
server_name my-website.com;
access_log /path/to/access/log/access.log;
error_log /path/to/error/log/error.log;
location / {
proxy_pass http://client;
}
location ~ /server/(?<section>.*) {
rewrite ^/server/(.*)$ /$1 break;
proxy_pass http://server;
}
}
Here my-website.com
will be the resultant name of the website where the code will be accessible (name of the proxy website).
Once nginx is configured this way. You will need to modify the requests such that:
- All API calls change from
my-server.com/<API-path>
tomy-website.com/server/<API-path>
In case you are not familiar with nginx I would advise you to go through the documentation.
To explain what is happening in the configuration above in brief:
- The
upstream
s define the actual servers to whom the requests will be redirected - The
server
block is used to define the actual behaviour of the nginx server. - In case there are multiple server blocks the
server_name
is used to identify the block which will be used to handle the current request. - The
error_log
andaccess_log
directives are used to define the locations of the log files (used for debugging) - The
location
blocks define the handling of different types of requests:- The first location block handles all requests starting with
/
all these requests are redirected to the client - The second location block handles all requests starting with
/server/<API-path>
. We will be redirecting all such requests to the server.
- The first location block handles all requests starting with
Note: /server
here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server
in all such use cases. It can be changed to any other string eg. /my-server/<API-path>
, /abc/<API-path>
, etc.
Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.
If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.
How to allow CORS in react.js?
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.
ReactJS: has been blocked by CORS policy: Response to preflight request doesn't pass access control check
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross-domain.
You can temporarily solve this issue by a chrome plugin called CORS.
copied from: How to allow CORS in react.js?
Reference: How to overcome the CORS issue in ReactJS?
How to resolve CORS error in REACT with ASP.NET Core
Fei Han and Jonathan Alfaro put me in the right direction and I finally found the solution. As Fei Han rightly points out in his answer, the CORS preflight requests are always anonymous and they use an HTTP OPTIONS method. So, here's what I did to resolve the issue.
- Enable anonymous authentication in
launchSettings.json
:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:62682",
"sslPort": 44376
}
},
- Create an Authenitcation Middleware like below, that returns 401 if the http request has any method other than
OPTIONS
and the user is not authenticated.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Server
{
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
BeginInvoke(context);
await _next.Invoke(context);
}
private async void BeginInvoke(HttpContext context)
{
if (context.Request.Method != "OPTIONS" && !context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Not Authenticated");
}
}
}
}
- Use the middleware in
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseHttpsRedirection();
app.UseRouting();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Axios having CORS issue
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
ReactJS API Data Fetching CORS error
The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:
The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-app
provides an easy way to do this: in your package.json
file, simply chuck "proxy": "http://your-company-api-domain"
. For more details, please see this link
Then in your react app you can using relative URL like this: fetch('/api/endpoints')
. Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.
Related Topics
How to Check If String Contains Substring
Convert Js Object to Form Data
Incorrect Result in JavaScript Calculation
Js Function to Calculate Complementary Colour
Remove HTML Tags in JavaScript with Regex
Referencing Another Schema in Mongoose
How to Clone a JavaScript Object Except for One Key
Clearrect Function Doesn't Clear the Canvas
Watch Multiple $Scope Attributes
What Is a Practical Use for a Closure in JavaScript
How to Get the Global Object in JavaScript
How Is JavaScript Single Threaded