CORs issue in axios using React - reactjs

So I've researched the web and tried almost all the solutions on their for this issue I am having with CORs using yelps fusion API. I'm using react but trying to call this API with axios. Here is my code.
static YelpApiSearch(searchedCity, onSuccess, onError) {
const config = {
Authorization: process.env.REACT_APP_KEY
Origin: "https://vendors.test"
};
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios
.get(`https://corsanywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?categories=foodtrucks&location=${searchedCity}`,
{
withCredentials: true,
headers: config
}
)
.then(onSuccess)
.catch(onError); }
Refused to set unsafe header origin error
Any help would be appreciated. Thanks!

This isn't a CORS problem per se. The error message tells you what the problem is.
Refused to set unsafe header origin error
You can't specify the Origin header. It is determined by the browser. If you could specify it, it would break a large part of CORS's security.
Remove your attempt to specify it from the config object.

Related

React JS: CORS Error causing NetworkError when attempting to fetch resource

I already found this which already helped me, but after adding the header like this in my proxy.js:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(function(req, res, next) {
//adding headers to allow CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(proxy('/api', { target: 'http://localhost:8080' }));
}
At the fetch() i also added the header to make sure it works:
fetch('http://localhost:8080/api',{
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(console.log)
}
I still get the error: TypeError: "NetworkError when attempting to fetch resource."
this.setState({ contacts: data }) should store the JSON Objects that gets delivered by my Backend Java Programm. The JSON Objects are at localhost:8080/api and are just Strings
My React Frontend runs on localhost:3000
The Response Header looks like this
Where do I need this header in order to not get the CORS error, preferable I would like to work without the npm library "cors", or any browser add-on. I should also replace the '*' with localhost:8080 If I am not mistaken, right?
My finishing goal would be to put these Strings in a PrimeReact Component (A Table) dynamically.
Edit: Full error message requested by sideshowbarker:
Warning:
Cross-origin request blocked: The same source rule prohibits reading the external resource at http://localhost:8080/api. (reason: CORS preflight channel was not successful).
Warning:
Cross-origin request blocked: The same source rule prohibits reading the external resource at http://localhost:8080/api. (Reason: CORS preflight channel failed).
ERROR:
TypeError: "NetworkError when attempting to fetch resource.
//It's in German so I couldn't upload a screenshot, translated it
I forgot to mention that i put #CrossOrigin on my Restcontroller too
Cannot comment because of low rep, but have you set app.listen(8080); ?
Also I don't think you need to change anything relating to CORS if you are running both at localhost.
Could you perhaps have something change in your browser that could be causing this? Try different browser?
Also I would recommend using axios, defining it to be GET on front and back, making sure when you go to http://localhost:8080/api on browser you get the JSON on your screen.
After countless hours of debugging it turns out that I didnt put an http.cors(); into my WebSecurityConfig.java
I discovered this after i read this tutorial:
https://www.baeldung.com/spring-security-cors-preflight

Status 7: Can't GET movie by ID using TMDB API

I'm trying to use the TMDB API to create a simple app. I'm using Axios to make the HTTP requests.
I started by retrieving the 20 latest movies, so far so good, manage to display that no problems.
The issue begin when I tried to get the details for a single movie. Searched some solutions but it seems to always present the same error: "Status 7: Invalid API key (or Status 401)".
This is my Axios config:
const BASE_URL = 'http://localhost:3000/';
const HEADERS = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
const PARAMS = {
params: {
api_key: 'xxxxxxxxxxxxxxxxxxxxxxxx',
}
};
const client = axios.create({
BASE_URL,
HEADERS,
PARAMS,
});
In a previous iteration I've tried including the API key has a 'Authorization' header, but it had the same problem.
By the status code, you may be quick to think something is wrong with my API key, but that doesn't seems to be an issue getting the latest movies, plus the I've triple checked it by now.
EDIT: I'm using ReactJS and Redux, I'm sure the problem doesn't come from there, seen I've use basically the same configuration with a local server, before starting this project, and without an API key there was no issue.
Solved the issue. The problem was a CORS issue, I was trying to make request without the CORS headers. Plus my Axios config was wrong.
The way I solve it was by using CORS Anywhere, with my API BASE URL:
const BASE_URL = "https://cors-anywhere.herokuapp.com/https://api.themoviedb.org/3";
I saw other ways of adding the CORS headers, including a chrome extension called CORS, but that would cause other issues. So I guess this is the simplest solution.

Access to XMLHttpRequest blocked by CORS Policy in ReactJS using Axios

I'm setting up stripe connect button in my React Component using Axios. I keep getting this error after redirection
Access to XMLHttpRequest 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: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
I get the code from the url and create a curl request using axios.Post. This is the code in my redirect URL
// Thankyou.js
export default class Thankyou extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const code = qs.parse(this.props.location.search, {
ignoreQueryPrefix: true
}).code;
const params = {
client_id: "*******************",
client_secret: "**********************",
grant_type: "authorization_code",
code: code
};
axios
.post(
"https://connect.stripe.com/oauth/token",
// apiBaseUrl,
{ params }
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
console.log(code);
}
render() {
return (
<div>
<h2>Thank you for connecting with us!</h2>
</div>
);
}
}
There is nothing wrong with your code, but most likely the API endpoint the code trying to reach is not setup for JavaScript web app. CORS policy is set on the server-side and enforced primarily on the browser-side.
The best way to work around is to use Stripe's JavaScript solution such as Strip React Elements or Stripe.js.
A hacky way to get around CORS would be setting up Reverse proxy with solutions such as NGINX. For example, you can use the following nginx configuration:
server {
listen 8080;
server_name _;
location / {
proxy_pass http://your-web-app:2020/;
}
location /stripe/ {
proxy_pass https://connect.stripe.com/;
}
}
By doing so, all the API calls to Stripe.com could be through /stripe under your web app's URL. For example, calling http://yourapp/stripe/oauth/token would be same as calling https://connect.stripe.com/oauth/token
That being said, the second solution is hacky and Stripe may decide to block your reverse proxy server.
basically you need to talk to whoever is hosting this https://connect.stripe.com/oauth/token to enable CORS (Cross Origin Resource Sharing )
It is a security measure implemented by most standard browsers to stop unwanted requests to your backend
It's probably because Stripe doesn't provide JavaScript client so you either have to use your own server proxy or use something like "https://cors-anywhere.herokuapp.com/https://connect.stripe.com/oauth/token"
I hope this answer would be useful to new users:
This issue can be easily fixed by using an annotation in your spring boot rest controller class.
Something like below (also ref screenshot):
#CrossOrigin(origins = "http://localhost:4200")
Explicitly mention the react JS server URL that is causing this issue.
Now after adding above annotation (with your react JS server URL) the browser will allow the flow.
All the best.
Learn about CORS
Think about it, there is anything wrong with your axios.post request, it's successfully contacting the server. But there is one more thing to do before the server let you execute or manipulate it's files.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.
So your cross-origin request and the server Cross-Origin Resource Sharing (CORS) have to match.
How do you solve it?
Depending on your server and the server side programming language your are implementing, you can configure the different parameters to handle your CORS.
For example, you can configure that the only allowed methods will be:
GET HEAD
So if someone try to axios.post to your server with a different method like POST, it will return an error like this:
Access to XMLHttpRequest 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: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Resources:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I would suggest reading through this site: https://stripe.com/docs/recipes/elements-react
It gives specific instructions straight from stripe on using their API with react. Good luck!

Firebase CORS issue

I built a react app and I have deployed it on firebase. I have been getting this error whenever user searches.
Failed to load https://food2fork.com/api/search?key=0882376145a8bcae6c3cee&q=fish&count=50: Redirect from
'https://food2fork.com/api/search?key=0882376145a8107c5946c3cee&q=fish&count=50' to
'https://www.food2fork.com/api/search
key=0882376145a8bcae390107c5946c3cee&q=fish&count=50'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'https://recipe-finder-26e0e.firebaseapp.com' is therefore not allowed access.
As I am new to this one, I am unable to figure out how to enable CORS in firebase which I think is the problem. If anyone can tell me how to enable CORS I would be grateful Thank you.
Edit: Source code link --> https://github.com/AdiBev/Recipe-Finder
Update: I didn't understand in the beginning that CORS needs to be handled by back end. Thanks to #Ben. Ayoub for explaining it to me.
If it helps for any others like me who got same problem I found a great article and some proxies are mentioned there.
link ---> https://gist.github.com/jesperorb/6ca596217c8dfba237744966c2b5ab1e
In addition to Ben. Ayoub's solution it could be worth you looking into HTTPS Callable functions if it's only your app trying to communicate with the Function and it's not part of a wider external API.
They work similar to HTTPS endpoints but get rid of the headaches of CORS.
import * as functions from 'firebase-functions';
export const listener = functions.https.onCall((data, context) => {
if (data) {
throw new functions.https.HttpsError('invalid-argument');
}
return {
some: 'json',
};
}
You don't need to use the request and response parameters like in the HTTP Endpoint Cloud Function.
It accepts JSON as it's context and returns a simple JSON object.
Edit
To answer your original question, the cloud functions can make use of CORS
import * as functions from 'firebase-functions';
const cors = require('cors')({ origin: true });
export const listener = functions.https.onRequest((req, res) => {
cors(req, res, () => {
return;
});
// cloud function logic
res.json({ some: 'json' });
});

Access-Control-Allow-Origin error while trying to access url using typescript and angular2

I am trying to retrieve a service which is running on another port.I am getting an error as follows
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:3000' is therefore not allowed access.
my service.ts file is as follows
getDeviceInfo(){
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000',);
headers.append('Access-Control-Allow-Headers','Authorization')
let options = new RequestOptions({
method: RequestMethod.Get,
url: DEVICE_URL,
headers: headers
});
return this.http.request(new Request(options))
.map((res: Response) => res.json());
}
thanks in advance
As per browser policy CORS is not allowed. Howerver if you are using chrome extension POSTMAN or app such as INSOMINA cors error wont occur.
How to pass cors error?
CORS error should only pass by server side.
Consider if your are using express as your server side. Then add following middleware in you app route.
app.use(function(req,res){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Header' , 'authorization');
});
You simply can't. Try Oauth to get information/data from other websites.

Resources