Getting tweets with React - javascript

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.

Related

CORS Error while fetching data from Wiki Js (GraphQL)

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

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

React API Fetch fail

I am trying to create a site where I will consume a web-api and display "users" on the site. I have an API-key that I have to put in the header as "x-api-key".
This is my code at the moment:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
items: []
}
}
componentDidMount() {
const myHeaders = new Headers();
myHeaders.append('x-api-key', 'KEY_HERE');
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
myHeaders.append('cache-control', 'no-cache')
fetch('URL_HERE', {
method: 'GET',
headers: myHeaders,
async: true,
})
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
})
});
}
render() {
var{isLoaded, items} = this.state;
if(!isLoaded) {
return <div>Loading...</div>;
}
else{
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.id}>
Name: {item.name} | Id:{item.id}
</li>
))};
</ul>
</div>
);
}
}
}
export default App;
The problem is I get these error messages in the console:
Failed to load http://URL/users: Response for preflight does not have
HTTP ok status.
Uncaught (in promise) TypeError: Failed to fetch
When I tried making a GET call in Postman I succeeded. So I suppose the problem is that the api-key doesnt get implemented in the header properly.
Appreciate the help, please let me know if there is anything else you need to know!
You need to remove below line from your code and after that, you need to handle OPTIONS method from server-side.
myHeaders.append('cache-control', 'no-cache')
You are getting this error because you are adding a header with 'x-api-key'. you have made the request complex. This requires the browser to make a preflight OPTIONS request to ask for permission to send the complex request.
The server you are making the request to is responding saying that OPTIONS requests are not allowed to that URL
You will need to modify the server and handle OPTION method properly so that it responds appropriately to the preflight CORS request.
You are not getting this error in postman because Postman doesn't need to make a preflight request.
Try to use axios if you want to fetch data using api.
It can be used at client side and server side as well and very much easy as well.
Here is the GitHub repo for your guide.
https://github.com/axios/axios

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

Categories

Resources