On redash I have a query. It's GET request. On POSTMAN it works well.
Query example:
https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key>
But on axios it throws:
Network error
And on console written:
Access to XMLHttpRequest at https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key> 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.
My axios default configs:
import axios from 'axios/index';
import { appVersion } from '../../constants/defaultValues';
const { CancelToken } = axios;
export const source = CancelToken.source();
const api = axios.create({
timeout: 5 * 60 * 1000,
headers: {
version: appVersion,
},
cancelToken: source.token,
});
export default api;
It's not from your code. your code is right
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.
You can read more about Cross-Origin Resource Sharing
Related
I'm getting CORS error while fetching data from wiki js graphql endpoint in my react app. I'm using REACT SSR.
here is what I'm doing
App.js
const client = new ApolloClient({
uri: 'https://example-wiki.herokuapp.com/graphql',
cache: new InMemoryCache(),
headers: {
Authorization:
'Bearer exampleToken1234abc',
},
});
api.js
import { useQuery, gql } from '#apollo/client';
const ALL_PAGES_QUERY = gql`
query PageQuery {
pages {
list {
id
title
tags
}
}
}
`;
export const getAllPages = () => {
const { loading, error, data } = useQuery(ALL_PAGES_QUERY);
return {
loading,
error,
data,
};
};
error
Access to fetch at 'https://example-wiki.herokuapp.com/graphql' 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.
enter image description here
enter image description here
I've already tried this solution
https://github.com/requarks/wiki/discussions/3056
provided by one of the maintainer of Wiki Js. but its not working at all
My .env (in root dir):
REACT_APP_ID = '123456';
REACT_APP_KEY = 'abcde123';
in app.js:
useEffect(() => {
getRecipes();
}, [query]);
const getRecipes = async () => {
const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${process.env.REACT_APP_ID}&app_key=${process.env.REACT_APP_KEY}`); //change the elements in the query to match ur ID and KEY + query
const data = await response.json();
console.log(data.hits);
setRecipes(data.hits);
}
However, it doesn't work. Error thrown in console:
Access to fetch at 'https://api.edamam.com/search?q=paneer&app_id=***;&app_key=***;' from origin 'http://localhost:3000' 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.
Failed to load resource: net::ERR_FAILED
I've tried restarted the server by npm start but it doesn't work.
How to fix this?
The problem is not related to ReactJS here. The issue you are facing is about the CORS policy which is related to the networks and headers of the response. you should have something like this in your request header:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Also try to use fetch with credentials included, something like this:
fetch(https://api.edamam.com/search?q=${query}&app_id=${process.env.REACT_APP_ID}&app_key=${process.env.REACT_APP_KEY}`, {
credentials: 'include'
});
When I make a GET request inside in react, I get blocked by CORS policy error. However if I make the same request inside vanilla js (a simple .js file) I get the appropriate response.
Here is my code in the react:
const axios = require('axios');
function getLatestPrice() {
const config = {
url: 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000',
method: 'GET'
};
return axios(config);
}
exports.getLatestPrice = getLatestPrice;
I get the following error:
Access to XMLHttpRequest at 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code in vanilla js file
const axios = require('axios');
const url = "https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000";
const config = {
url: url,
method: "GET"
};
axios(config).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
});
Here I am getting the correct response. The postman request to the same is also working.
(I am not controlling the API backend)
I am trying to set up an AWS lambda function, however when I call the endpoint, I am getting this error message back in the console.
Access to fetch at 'https://*.execute-api.eu-west-1.amazonaws.com/default/' from origin 'http://localhost:3000' 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 have set the CORS policy on the AWS Gateway
Here is my request code... I am just trying to print out the body of the response for testing purposes.
const response = await fetch(
'https://**********.execute-api.eu-west-1.amazonaws.com/default/**************',
{
method: 'POST',
body: "{'test': 'test'}",
headers: {
'X-Api-Key': '*****************************',
},
}
);
const text: any = await response.text();
console.log(text);
Weirdly when I look in fiddler, it is sending the OPTIONS and also returning a correct response, which is currently just printing out the different headers passed to the function.
If you've lambda proxy integration enabled you'll have to add headers from lambda.
From AWS documentation CORS section
For a Lambda proxy integration or HTTP proxy integration, you can still set up the required OPTIONS response headers in API Gateway. However, your backend is responsible for returning the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response.
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
you can read more here
I want to use /data/todo.js file in my reactjs component. I have used axios http request to get this data in my react component i.e.,
import React, { Component } from 'react';
import axios from 'axios';
class TodoList extends Component {
componentWillMount() {
var config = {
headers: {
"Access-Control-Allow-Origin": "http://localhost:8080/",
"Access-Control-Allow-Credentials": true
}
};
axios.get('http://abc.mydomain.org/data/todo.js', config)
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<div className="todo-list"></div>
);
}
}
export default TodoList;
It gives an error
XMLHttpRequest cannot load http://abc.mydomain.org/data/todo.js. 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.
You are trying to access a cross-origin HTTP request from you application, which is by default blocked by the browser.
To access the resource, Cross-Origin Resource Sharing (CORS) should be enabled at the application you are trying to access (In your case http://abc.mydomain.org)
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. This means that a web
application using those APIs can only request HTTP resources from the
same domain the application was loaded from unless CORS headers are
used.
You can check more on this here