React axios CORS issue - reactjs

I am sending CORS request as follows:
const axiosConfig = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//'crossdomain' : true
// 'Access-Control-Allow-Origin': '*'
}
};
let netAddress=https://some port/
axios.post(netAddress, obj, axiosConfig)
where obj is the data object.
Also, i am running npm start as below for React app
set HTTPS=TRUE&&npm start
The headers accepted by the server are as follows:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-methods:GET , POST , PUT, PATCH ,DELETE
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:x-paging-pageno,x-paging-pagesize,x-paging-totalpage,
x-pagingtotalrecordcount
I am getting error as follows:
Access to XMLHttpRequest at 'https://10.6.0.7:9022/api/event/Event' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My localhost as well as server are running on HTTPS. I have tried crossdomain and Access-Control-Allow-Origin, but its not working still
Also, GET requests to the same server is successfull, but POST fails
And, I tried with chrome extensions like CORS unblock, but its failing
Please help

This may not be the answer you are looking for but I had this issue recently trying to POST to an endpoint from my client and was not able to due to CORS. It was a browser issue, not an issue with what the server accepted. You can get this to work by writing a cloud function which does the POST to your endpoint and then call that cloud function from your client. Be aware that you cant make http requests in cloud functions without at least the Blaze plan. Again, sorry if this doesnt help but thought I would share.

Related

Invoke AWS lambda from react application

I've developed an AWS function with .net core, it's been deployed to AWS and I can call it from Postman and seems everything's ok, but when I try to call it from a react application with Axios library I get this error:
(index):1 Access to XMLHttpRequest at 'https://awsfunctionurl/api/Organisations' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
here is the code to call the API:
const response: Response = await axios.get(url,{
headers:{
"content-type": "application/json; charset=utf-8",
"Authorization": `Bearer ${accesToken}`
},
})
When I remove Authorization header it starts working!
If you are running the request from a local browser, it will block the pre-flight request by default. There are workarounds for this, depending on the browser. See here, for example, for Chrome.
Alternatively, it may be easier to just add '"Access-Control-Allow-Origin": "*"' in your response headers from the lambda function itself.

How to How to fix "No 'Access-Control-Allow-Origin' header is present on the requested resource" in post call in reactJS using Fetch method

Getting below error while i call DotNet core API method from ReactJS post call using Fetch options.
ReactJS post call only i am getting this error, below way i was tried.
Jquery get/post request - working fine
Postman get/post request - working fine
Swagger get/post request - working fine
ReactJS get request - working fine
ReactJS post request - Not working fine
"Access to fetch at 'https://localhost:44352/api/Address/CheckAvailability' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
/*ReactJS Code: */
export function saveAddress(address) {
return fetch(baseURL + "Address/CheckAvailability", {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(address),
}).then(handleResponse)
.catch(handleError);
}
/*Dot.Net core Code: */
[HttpPost]
public ActionResult CheckAvailability([FromBody]ReqAddressDetailsDto request)
{
if ((request) == null)
{
return NotFound();
}
return Ok(request);
}
If your client application (the React web app) is on another scheme (any of http/https, domain or port is different), you need to have CORS enabled on your ASP.NET Core back-end.
In the Startup.cs file, you need to add this:
In ConfigureServices()
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins("http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
In Configure() put this just before app.UseMvc():
app.UseCors();
Check this link for more info:
https://learn.microsoft.com/en-us/aspnet/core/security/cors
did you enabled / configured cors in this .net core api?
How to enable CORS in ASP.NET Core
You can check CORS headers on your backend script.
The CORS standard manages cross-origin requests by adding new HTTP headers to the standard list of headers. The following are the new HTTP headers added by the CORS standard:
Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Request-Headers
Access-Control-Request-Method
Origin
These headers are all important, but let’s we focus on the following header:
Access-Control-Allow-Origin
You should define Access-Control-Allow-Origin header as '*'. I guess, it may be solved your problem simply. A little example for PHP:
<?php
header("Access-Control-Allow-Origin: *");
You may find an info of each CORS header the following: CORS Headers.
If you want to learn more details about CORS, You can follow this link.
This status code is a useful hint to understand that the server doesn’t support OPTIONS requests.
Add the corresponding header on the server side when handling the OPTIONS method. We will then have the following requests:
Access-Control-Allow-Headers : Content-type
Hopefully this solves .

How do I fix a network error received from axios response reactjs

I'm making a post request using axios in reactjs after users login. Here it is:
axios.post('https://localhost:3000/api/login/authentication', {
email: email,
password: password
})
.then(response => {
this.props.history.push('/Main')
})
.catch(error => {
console.log(error)
})
It goes in the error and I log it to the console. This is what I get:
Error: "Network Error"
createErrorhttp://localhost:3000/static/js/0.chunk.js:26742:15 handleErrorhttp://localhost:3000/static/js/0.chunk.js:26293:14
Also in case it's any help, I get this warning before the error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:3000/api/login/authentication. (Reason: CORS request did not succeed)
Can anyone please help me solve this issue? Thanks in advance!
If you're using a front-end application that makes request to a back-end API, you need to include certain headers in the API server if the API server is running on a different port.
For example, if you're serving a ReactJS application with webpack in development mode, webpack acts as a server, sending the reactJS application to the client. Then, making requests to the API server will require that the API server, running on a different port, include Access-Control-Allow-Origin headers in all http responses.
Basically, before generating every response, you need to set 'Access-Control-Allow-Origin' to localhost:<port you visit in the browser>.
In a basic express app, you can paste this in your app.js file, for example:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
Note: If you may need to change http://localhost:3001 to match the port you visit in the browser.
EDIT: OP is not using express, but is using Webpack. The question is: What is an express-agnostic solution?
Answer: The solution is still the same: regardless of what API server you are using, just set the response headers for every response.
There is another solution that involves Webpack, though:
In the package.json file of your front end code that's being served with webpack, add the following: "proxy" :"http://localhost:<port API server is running on>"
For example, is webpack is serving your front end app to localhost:3000 and your api server is running on localhost:3001, then the proxy in package.json would be:
"proxy":"http://localhost:3001"
You can add the CORS header in webpack dev server config as follows:
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
},
This will add these two headers in your response. Hence solve your problem. However, when your services run on a different server other than your local machine, these headers need to be added in server response.
The very first thing that i am figuring out in your code is that you are using 'https' but it should be only 'http'to make request, because local host uses http.
2)This might be due to cors, Before making any requests , the browser sends a pre-flight request to the API server to know that "This website has been allowed to access your resources or not", so using cors and specifying origin which can access API resources will solve this problem.

Access token with Axios gets the following error: Response for preflight has invalid HTTP status code 401

I'm trying to request the access token with Axios in my SpringBoot + React application.
axios.post("http://localhost:8080/oauth/access_token", 'grant_type=password&username='+username+'&password='+password,
{ headers: {
'Authorization': 'Basic ' + btoa("clientid:clientsecret"),
'Content-Type': 'application/x-www-form-urlencoded,charset=UTF-8'
}
But I'm always getting the following error: "Response for preflight has invalid HTTP status code 401".
I tried the request with Postman and it works always.
Thanks!
The problem is that the Resource Owner Password Credentials grant, you are trying to use, is not suitable for JavaScript applications running in a browser, because you cannot keep the password safe in a browser. That's also the reason why the token endpoint (/access_token in your case) doesn't support CORS HTTP headers and the XHR request from your question fails.
Unlike browser, Postman doesn't require the CORS headers and doesn't issue the OPTIONS request before the actual request, so it works.
Try to use the Implicit grant flow which is designed for browser applications.

How to make this Angular http get request (with basic authentication) work?

I am trying to debug my angular app with chrome dev console.I want to send a get request to a local server from angular. I've tried the following:
$http = angular.element($0).injector().get('$http');
$base64 = angular.element($0).injector().get('$base64');
var auth = $base64.encode("user:passwd");
var authHeaders = {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"};
$http.get("url",{headers:authHeaders,method:"GET"})
After reading this answer:
https://stackoverflow.com/a/30296149/1496826
I thought that custom header is the problem. So, I tried putting the authorization headers in the body:
$http.get("url",{data: {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"},method:"GET"})
But I am still getting the same error:
XMLHttpRequest cannot load "url". No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'null' is
therefore not allowed access. The response had HTTP status code 401.
This same get request works fine from Postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "url",
"method": "GET",
"headers": {
"authorization": "Basic bWdhcasdasd",
"cache-control": "no-cache",
"postman-token": "XXXXXX-XXXXXX-xXXXX-xXXXX"
}
}
I have tried several other variation like - $http default / common header etc. but everything failed. Please help.
this is a CORS issue.
CORS headers must be handled server side, i don't see your server side code here but in order to let this error disappear you must specify which domain are allowed to request resources.
the exception is caused by the browser that intercept the server response check the headers and if it doesn't find the Allow-Control-Allow-Origin header it won't forward the response to your code (this happens only for cross origin request).
This is why Postman let you see the response, because it doesn't do what chrome does, doesn't make any check.
As i said the correct solution is to fix your server side code and specify the Allow-Control-Allow-Origin header , alternatively a quick but temporary workaround is to install this plugin for chrome that will intercept the server response and add the Allow-Control-Allow-Origin to * (means any domain) this trick will fool chrome and make you see the response.

Resources