API request blocked by CORS - javascript

I'm trying to use the g-trends API in my vuejs application running from localhost, but keep running into issues of my requests getting blocked due to CORS restrictions: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I know how to fix the issue when performing a fetch request, but not in a scenario where I don't actually see the request URL like when using an API. Is there a way to fix this?
const { ExploreTrendRequest } = require('g-trends');
const explorer = new ExploreTrendRequest();
explorer.past5Years()
.addKeyword("keyword")
.download().then(csv => {
console.log(csv)
})

I usually use a proxy server for avoiding this situation, your app asks your server to do that request for you so the communication with the API is managed by your server, when your server receives the answer it forwards it to your app and there won´t be any CORS problem.

Related

How to solve CORS error while fetching an external API?

I'm developing a web app in Angular 10 that works as follows:
I'm dealing with CORS issue. I do not have permission to add code to the server I'm fetching.
I want to be able to:
Fetch the website
Parse the result, and put it in my database
I'm aiming to deploy the solution on an Apache server.
Here is the CORS error I'm dealing with:
Blocking a Cross-Origin Request: The "Same Origin" policy does not
allow viewing the remote resource located at
https://wwwfrance1.CENSORED.eu.com/api/?apikey=CENSORED.
Reason: "Access-Control-Allow-Origin" CORS header is missing. Status
code: 200.
Here is what i've tried:
Using MOSIF mozilla extension (works, but not sustainable for deployment, and for some reason, when I'm ignoring the CORS security, I cannot post on my DB any more)
Adding a header in my fetching request, such as:
/******API SEACH****/
/***Global Update***/
private updateClients() {
let xmlRequestPromise = fetch('https://wwwfrance1.CENSORED.eu.com/api/?apikey=CENSORED&service=list_clients', {
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
}
})
.then(async response => this.clients = this.regexSearchClient(await response.text()))
return xmlRequestPromise
}
But that doesn't work either. I've verified that the header appears in the request.
How to proceed?
What is CORS ?
Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. From wiki
In simple terms only an internal webserver can send Requests which are potentially dangerous to it's web server, and requests from other server's are simply blocked.
But few HTTP requests are allowed ,Few of the allowed methods are GET, HEAD, POST.
How do I resolve the issue ?
Apparently in this circumstance you cannot send a fetch request to a web server having CORS header. Instead you can do a GET request to the web server as a web server having CORS allows HTTP GET requests.
Note - If you send a GET request to a web server using angular in your browser it wouldn't work as browser's convert GET requests into fetch requests and fetch requests aren't allowed from a web server with CORS. Instead send a GET request from a webserver/local machine rather than a browser.
Create your own server and make a route which fetches that API. From your Angular application fetch that route on your server.
You have to use a package as a middleware. If you are using nodejs-framework expressjs.At first, you have to run npm install cors -force.Then add the code that is given bellow:-
const cors=require('cors')
app.use(cors({origin:true}))

Axios hitting No 'Access-Control-Allow-Origin' header is present on the requested resource error

https://samples.openweathermap.org/data/2.5/forecast?appid=be2e163d03a0b97a96a89b0230be8e4a&q=klang,my
When I directly paste the URL into the browser, I can make the API request successfully. However, when I try it with Axios I'm hitting below exception
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Based on some research,
I can't understand the logic behind as I'm following the exact same steps provided by online course, by simply firing this API call using Axios should be able to return the result.
import axios from 'axios';
const API_KEY = 'be2e163d03a0b97a96a89b0230be8e4a';
const ROOT_URL = `https://samples.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`
export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city) {
const url = `${ROOT_URL}&q=${city},my`;
const request = axios.get(url);
return {
type: FETCH_WEATHER,
payload: request
}
}
This exception means the server your hitting does not support CORS (Cross-Origin Resource Sharing).
In the case of openweathermap.org I think you should be using api.openweathermap.org instead of samples.openweathermap.org
Here are the few things i observed:
You are using the sample api(“samples.openweathermap.org”) not the production one(“api.openweathermap.org”) so i think for integration with application you should use production API.On this they give the CORS support.
If you still want to check with sample api endpoint then
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin'header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Reference: https://openweathermap.desk.com/customer/portal/questions/16823835-cors
You need to add cors in your server app
var cors = require('cors');
app.use(cors());
Hope this help
When you directly access the url in browser there is no cross domain request is issued.
But when you access the resource using axios there might be a chance that you are accessing resource on different domain then the domain present on your browser tab.That is the reason you are getting Access-Control-Allow-Origin not present. For handling this add a logic on server side to add this header in OPTION Response.

'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.

CORS issue performing api calls in react/redux application

I was trying to implement a mailchimp api and came across a cross domain issue with an error in chrome like this:
XMLHttpRequest cannot load https://us9.api.mailchimp.com/3.0/members.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example.com' is therefore not allowed
access. The response had HTTP status code 501.
After some research it turns out that api calls I make are made from the browser (I simply call api from one of my actions), but to fix this issue they need to be made on the server.
Hence I am trying to figure out a way to call an api from the server inside of my action, to bypass this issue.
EDIT:
One of the solutions I found is to use jsonp for this, however I had to drop it as well, as I can't authenticate with it.
The solution I found is to proxy api calls through express in the following way:
In your express config:
import request from 'request'
app.use('/api', function (req, res) {
let url = 'your_api_url' + req.url
req.pipe(request(url)).pipe(res)
})
What this allows you to do is instead of calling https://myapi.com/endpoint in your components is to use /api/endpoint this way express will replace all instances of /api on your server with your api url and perform an api call from the server itself.

CORS request in react

Getting this error when trying to get stuff from the Twitter API using simple-twitter:
XMLHttpRequest cannot load https://api.twitter.com/1.1/statuses/user_timeline.json. 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
I'm basically doing exactly what it says in the react docs, but with the relevant line replaced:
componentDidMount: function() {
twitter.get('statuses/user_timeline', function(error, data) {
if(this.isMounted()){
this.setState({tweets: data})
console.dir('callback')
}
}.bind(this));
}
The callback function seems to never fire, which I assume is due to the request not completing.
What am I missing here?
The issue here is the module you're using is written for Node, not the browser.
Whilst in the browser, you can't make requests outside of your origin (in this case localhost:3000) unless the requested resource is served with the appropriate Access-Control-Allow-Origin header.
In this case the browser makes a preflight (OPTIONS) request to the same resource to see whether the CORS checks pass and it can safely respond. In this case it can't because Twitter's API doesn't allow your origin.
You can avoid these limitations if the API supports JSONP, but as of V1.1 of the Twitter API, only OAuth is supported.
This means that to access the Twitter API from the client, you'll need to authenticate inside your session, in order to generate an OAuth token that you can use to make requests. Take a look at the codebird-js library.
Alternatively, you can use the simple-twitter module from a server and forward requests from your browser on to the Twitter API.

Categories

Resources