CORS Error while fetching data from Wiki Js (GraphQL) - javascript

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

Related

Unable to access environment variables for api id and key in React App

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'
});

Axios GET request working in plain js but not working in react - CORS error

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)

redash GET request works on POSTMAN but not on axios

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

XMLHttpRequest cannot load http://abc.mydomain.org/data/todo.js

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

Getting tweets with React

I'm using the Twit package to pull tweets. I keep getting error 400, and
Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: 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. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The bulk of this was able to work with vanillajs, but once I imported into React, I've gotten these errors. How do I fix this? I've taken out the API keys for security.
import React, { Component } from 'react';
import Twit from 'twit';
export default class Twitter extends Component {
componentDidMount() {
const T = new Twit({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
})
let params = {
screen_name: 'twitterdev',
count: 10
};
function getData(err, data, response) {
let tweet = data;
for (var i = 0; i<tweet.length; i++) {
console.log(tweet[i].text);
console.log();
}
}
T.get('statuses/user_timeline', params, getData);
}
render() {
return(
<div></div>
)
}
}
The Twitter API does not support CORS requests. That's what you are trying to do. Accessing API from a different domain. You'll have to create a bespoke url at your local server that proxies the request to the Twitter
API.

Categories

Resources