How to solve "Getting blocked by CORS policy" when using twitter API in nodejs? - javascript

I have this block of code that I'm testing to see if it'll send a tweet if it's button is clicked.
const onTweet = () => {
client.post('statuses/update', {status: 'Testing'})
.then(function (tweet) {
console.log(tweet);
})
.catch(function (error) {
console.log(error + " error")
});
}
However, every time I click on the button I get this exact error
Access to fetch at 'https://api.twitter.com/1.1/statuses/update.json' from origin 'http://localhost:1234' 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.
I've tried to research online to see how to fix it or work around it, but I don't think the solution I've found apply to my problem. For example, this post Access to fetch at from origin 'http://localhost:3000' has been blocked by CORS policy, says to set the mode to no cors but I don't think that applies to my problem since I'm not using CORS to post this tweet. This is in nodeJS and the backend was built with firebase and react router dom.
Also, if someone can link the official twitter api nodejs documentation I'd appreciate it. Haven't found it if there is any.

It looks like twitter API doesn't have CORS support . You may try workarounds like extensions or Postman/Curl etc as mentioned here -
https://stackoverflow.com/a/35898961/7895283
https://twittercommunity.com/t/will-twitter-api-support-cors-headers-soon/28276/6

Related

Enable Cross-Origin Requests (CORS) in POCO C++ Libraries

I'm building a C++ backend with heavy calculations that are meant to work as an JSON API for connecting clients. To accomplish this, I've used HTTPServer in Poco::Net from POCO C++ Libraries.
Unfortunately when building two different clients it turned out that a regular webpage (HTML+JS) can't use Fetch to communicate with the backend due to CORS error. My understanding is that they need to use the same localhost: and that's not the case when manually opening the HTML document on the computer that's also running the backend.
All I can come up with when searching is the generic advice that servers need to enable CORS and whitelist relevant domains. Unfortunately I can't find documentation on how to accomplish this. The only relevant result was an answer on a related question where he recommended the following:
response.set("Access-Control-Allow-Origin", "*");
Naturally whitelisting everything isn't recommended from a security point of view but the main goal here is to just get it running locally to continue the development. Unfortunately it seems to make no difference and the browser console still says:
Access to fetch at 'http://localhost:6363/' from origin 'null' 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.
Hovering the error in the Chrome Network tab I get the following:
Cross-Origin Resource Sharing error: PreflightMissingAllowOriginHeader
My current JavaScript call:
const data = { test: 'test' }
fetch('http://localhost:6363', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.text())
.then(message => {
console.log('Data retrieved:', message);
})
.catch((error) => {
console.error('Error:', error);
});
Any suggestions on how to proceed?

Cannot call Apache Airflow REST API using JavaScript Fetch API (CORs Error)

Working with Apache Airflow REST API, and having issues with CORS.
When calling the endpoint using the fetch API in JavaScript I get the following error:
Access to fetch at 'my_url/api/v1/dags/example_bash_operator/tasks' from origin 'my_url' 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.
This is how I am calling it:
let url = "my_url/api/v1/dags/example_bash_operator/tasks";
let username = 'my_username';
let password = 'my_password';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {
headers: headers,
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
I also tried adding mode: 'no-cors' but just get the "unexpected end of input" error.
For some background, the following works fine:
starting the airflow webserver and scheduler
accessing the airflow UI
accessing the SwaggerUI authenticating Swagger and calling the REST endpoints with this tool
calling my_url in the address bar of a new browser tab (returns the expected JSON)
I have set the auth_backend in airflow.cfg:
auth_backend = airflow.api.auth.backend.default
Although with the latest REST API version I don't think this makes a difference since everything is set to deny.
I have also set the access control headers in airflow.cfg as described in the docs:
access_control_allow_headers = origin, content-type, accept
access_control_allow_methods = POST, GET, OPTIONS, DELETE
access_control_allow_origin = my_url
...and also tried with wildcard for the access_control_allow_origin:
access_control_allow_origin = *
So the REST calls work fine through Swagger and through the browser address bar, but I cannot call it with fetch using JS. Note that the JS is in an index.html file on the same server (and same root directory) as the airflow files.
The described behavior makes sense, since CORS is used by the browser to prevent attacks from scripts of different resources.
You are still able to fetch via Swagger, Postman or other tools, even through the browser via address bar. But if the policy does not allow to fetch from a different origin, then the browser prevents fetching from your script, which is probably served on a different port. Origin contains host and port.
Your main issue, I cannot help with at the moment.
I've faced the issue of not being able to set the origin policy within the Airflow 2.0 server/API through the (docker-compose) environment variable AIRFLOW__API__ACCESS_CONTROL_ALLOW_ORIGIN.
Maybe it's related to your issue, since I can see from the url of your question (containing the v1), that you're are also using Airflow 2.x.
By the way, the message from chrome is CORS error: Preflight Missing Allow Origin Header, referring to the question in the comments of the original question.

'Access-Control-Allow-Origin' error in request js

I'm writing an angular 2 app which uses a module called github-trend. I have a service which calls some functions from the module
scraper.scrapeTrendingRepos("").then(function(repos) {
repos.forEach(function(repo) {
//more code here
});
}).catch(function(err) {
console.log(err.message);
});
For now I'm testing my angular app with Chrome(56.0.2924.87) on http://localhost:3000/ and its giving me an Access-Control-Allow-Origin, here is full message:
Fetch API cannot load https://github.com/trending. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
data.service.ts:43 Failed to fetch
I've searched around and know that this might be happening because get request and server are working on differnt ports? Looking at the repo, the github-trend module using requestjs to make http requests but I'm not sure how to fix this. Is there a way I can make it work on chrome? What should I modify in the module code so as to make it work?
Solved the problem by using an Allow-Control-Allow-Origin extension for chrome.

Weather API request cors error

I am trying to get weather data from dark sky api and I keep getting a cors error.
Here is my code:
var url = `https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/${lat},${lon}`;
axios.get(url, config).then(response => {
this.setState({
...
})
}).catch(function (error) {
console.log(error);
});
I get an error "XMLHttpRequest cannot load https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/38.5815719,-121.4943996. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://ebcperez.github.io' is therefore not allowed access."
I got a same issue But i solved that
https://www.freecodecamp.org/forum/t/calling-openweathermap-api-is-blocked-due-to-cors-header-access-control-allow-origin-missing/191868
like this :
"https://cors-anywhere.herokuapp.com/http://samples.openweathermap.org/data/2.5/forecast?appid={your_Api_key}"
or https://api.openweathermap.org/data/2.5/forecast?appid=
So i don't know that url will be didn't occur error
Looks like the Darksky API server doesn't allow CORS, so you won't be able to make this request from your browser.
A possible solution would be to issue the API request from your application server, and then just display it on the front end.
Here’s an explanation of why this happens. The tl;dr is to use a CORS proxy for your requests. Prepend https://cors-anywhere.herokuapp.com/ to your API’s URL. https://cors-anywhere.herokuapp.com/http://api.openweathermap.org...
i hope this works for you

'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)

I'm getting an a "XMLHttpRequest cannot load https://example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access."
This is my componenDidMount(), and I'm using axios to get the data from my API.
componentDidMount() {
this.serverRequest = axios.get(this.props.source).then(event =>{
this.setState({
title: event.data[0].name
});
});
}
I'm using "python -m SimpleHTTPServer" on the terminal, to run 'http://localhost:8000'.
I'm using the Chrome browser, and if I turn on the Chrome CORS plugin (to enable cross origin resource sharing), the app works, and I see data displayed from the API on the DOM. But I know that using the CORS plugin is bad, so how should I fix the 'Access-Control-Allow-Origin' error officially?
With Axios, can I somehow add dataType: "jsonp", if that would fix it?
This is a restriction made by the browser for security reasons when you try to access content in some domain from another domain. You overcome this, you need to set the following in your header
Access-Control-Request-Method
Access-Control-Request-Headers
Many sites restrict CORS. The best way to achieve your goal is to make your python server as a proxy. See the example.
//Request from the client/browser
http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com
//In your server
1. Handle the request
2. Get the query param(url of the website)
3. Fetch it using your python server
4. Return the fetching data to the client.
This should work.

Categories

Resources