I have a problem with my cors policy between my backend (API Rest in .NET Core 6) and my frontend (in ReactJS), the thing is that in my backend I have the following configuration:
In appsetings.json:
"AllowedHosts": "mywebsite.com"
In Program.cs:
services.AddCors(options =>
{
options.AddPolicy(name: "mycors", builder =>
{
builder.WithOrigins("mywebsite.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("mycors");
This configuration doesn't work when I'm trying to fetch a post request to my API, but if I change the AllowedHosts to "AllowedHosts": "*" it works. I don't understand why I can't allow just to my frontend website.
Additional information, my post request has these parameters:
method: 'POST'
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referrer',
headers: { 'Content-Type': 'application/json' },
body: //My parameters
The console error is:
Access to fetch at 'mybackendpostmethod' from origin 'myfronturl.com' has been blocked by CORS policy: 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.
I solved putting my api that return as follows
Related
I am getting the cors policy error like this.
Access to fetch at 'my-url' from origin 'http://www.mywebsite.com' has been blocked by CORS policy:
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.
This is my code:
const requestOptionsBR = {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
}),
body: JSON.stringify({
action: "user_reports",
user_id: this.state.user_id,
start_date: this.convertDate(this.state.startDate),
end_date: this.convertDate(this.state.endDate),
}),
};
fetch(my-url, requestOptionsBR)
.then((res) => res.json())
.then((data) => {
this.setState({ loadingStatus: true });
console.log("User Reports", data)
if (data.status) {
this.setState({
user_data: data.params,
loadingStatus: false,
resultRetrieved: true,
});
this.generate_download_csv_data(data.params);
}
The above is working fine in local , but in production it is not working.
How to overcome this issue?
Any help would be great.
The wildcard * isn't allowed, as you must give a specific protocol, domain and port for security reasons.
More info here...
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
As the error message suggests, you can also set the option:
mode: 'no-cors'
...in your requestOptionsBR, however this will limit what you can put in your request headers.
More info here...
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
I am trying to integrate stripe payment gateway in my react project but cors related issue occur.
Can any one help me to resolve this.
"Access to fetch at 'https://connect.stripe.com/oauth/token' 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."
But it works fine when I am disabling the cors in chrome browser. Is there any alternate how to integrate stripe payment gateway in reactjs project?
My code:
const bodyFormData = new FormData()
bodyFormData.append("client_secret", "");
bodyFormData.append("code", code);
bodyFormData.append("grant_type", "authorization_code");
fetch("https://connect.stripe.com/oauth/token", {
method: 'POST',
body: JSON.stringify(userData),
headers:{
Accept:'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin':"*",
OPTIONS: '',
}
})
.then((response) => response.json())
.then((res) => {
console.log(res);
resolve(res);
})
.catch((error) => {
reject(error);
});
It looks like you're making that call to complete the connection from frontend React code in a browser. You can't do that and it will never work, since it uses your Stripe secret key which should never be on the frontend.
Instead you should make this call from a backend server route after the user is redirected from the OAuth page.
I am trying to call an api but it is giving me following error :
Access to fetch at 'https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01' 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.
I am using react and the code is :
try {
let url = `https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01`;
let response = await fetch(url,{
mode: 'cors', // no-cors,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
"Accept": 'application/json',
'Origin' : 'http://localhost:3000'
//'Content-Type': 'text/xml'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
});
this.setState(() => {
return {
searchResults : response
}
})
} catch (error) {
console.error(error);
}
please guide what to do
The error is due to CORS, there is nothing wrong with the front-end code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
To fix this issue, the server should set the CORS headers,
See here on how to enable CORS for your server
If your server is running express you need to set cors like this,
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use the cors middleware for express
Ext.Ajax.request({
url: 'https://dev-516799.oktapreview.com/api/v1/users?limit=200',
method: 'GET',
Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
headers: {
'Authorization': 'SSWS Token'
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
//'Access-Control-Allow-Methods': 'GET'
},
scope: this,
cleanup: function () {
view.setLoading(false);
},
success: function (response) {
}
But I am getting error as "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"
Access-control: Allow-Origin headers are a security feature that has to be enabled in the reply from the server, not in the request to the server.
Examples: ExtJS - Adding headers to AJAX store
In your case, you are at the mercy of Okta. They have some APIs that support CORS if you provide them with the allowed URLs, and others that don't. You cannot access Okta APIs directly from your JavaScript code unless the APIs are marked as CORS-enabled and you have added your URL to the list of CORS-enabled URLs in the Okta admin panel. If you need unmarked APIs or access from arbitrary URLs, you may have to create a wrapper in your own server backend that relays the requests from your frontend to the Okta server.
In my React app I am trying to make a GET request from my heroku server to get a list of users:
https://blablabla.heroku.com/users
using the following request:
const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})
function loadMyUsers(data) {
data.json().then((jsonData) => {
// console.log(jsonData)
})
}
sendSearch.then(loadMyUsers)}
However I get the following error:
Fetch API cannot load https://blablabla.heroku.com/users.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access. If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.
I tried changing my Fetch method to many things similar to:
const sendSearch = fetch('https://blablabla.heroku.com/users',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'mode': 'no-cors'
}
})
but the problem persists.
How do I make the cross domain request?
On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: http://localhost:8080 if you wish.
On your production server though, you probably won't need this header, unless you have very good reason for cross origin requests.