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.
Related
I have a website with React hosted on Firebase, with Django for backend running on a server with nginx.
On this website I have a form where the user can upload up to 3 images. On my local PC it works fine, but on the production environment I get this error when I try to upload big files (more than 5mb):
A server/network error occurred. Looks like CORS might be the problem. Sorry about this - we will get it fixed shortly.
Now the thing is that the images get uploaded normally, I can see them when I check the submitted form on the website admin area, but on the frontend, after submitting the form, instead of the success message I get that error.
I have incresed nginx client_max_body_size 15M, but I still get the error.
But given that the images do get uploaded, I think the max body size is not the problem.
I found the problem! It was a very dumb thing, but I didn't notice it before.
Basically I had this
const instance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
Authorization: accessToken
? 'JWT ' + accessToken
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
I set the timeout to 5000ms in axios. I changed it to 30000ms. All good.
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.
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.
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' });
});
I'm trying to make wordpress as a backend to my angularjs app, so I'm using the plugin rest-api with the jwt-auth
so when trying to login I get the following error
XMLHttpRequest cannot load http://localhost/back/wp-json/jwt-auth/v1/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://imider.ma' is therefore not allowed access. The response had HTTP status code 500.
I know i have to add CROS access, but I'm not familiar with wordpress, so any help?
https://docs.google.com/document/d/17zgUHZrvL5KVG2yKQE8NWgxNZn6V08xr65DBox5WVZ0/edit?usp=sharing
here is my tutorial of how to access the api
then you can use this to get the token
$http({
method:'post',
url:'',
data: {
username: '',
password: ''
}
}).then(function(results){
console.log(results);
})
then you can use this
$http({
method:'get',
url:'',
headers: { 'Authorization': 'Bearer <myTokenId>' }
}).then(function(results){
console.log(results);
})
I created a video detailing the process of installing and setting up the plugin. If you follow the steps I outlined there you should be good.
https://youtu.be/Mp7T7x1oxDk
The idea is that you also need to modify .htaccess and wp-config.php to make the plugin work with the existing API endpoints as well.
Just by installing the plugin and adding a SECRET_KEY, used to sign the token will make the JWT setup work but it will not allow you to use the tokens generated through that API with the existing REST API endpoints.