Reading json content from a REST API URL - javascript

I have built a REST API with Node.js Express http://localhost:3000/api/feeds with node.js and filled with data.
router.get('/api/feeds', function (req, res, next) {
documentDBConfig.getAllDocuments()
.then(() => res.json(documentDBConfig.feedsArray));
});
Now i make a static website and want to use javascript or jquery to get data from my REST API. I used this code
$.getJSON( "http://localhost:3000/api/feeds", function( data ) {
console.log(data);
});
But it keeps saying
XMLHttpRequest cannot load http://localhost:3000/api/feeds. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I know i'm doing it wrong, but i couldn't find the correct way. How can i get this json content with my website from my REST API (http://localhost:3000/api/feeds) ?
Edit: I don't get this warning with explorer, but i can not get the content. And now i solved the chrome problem thus i don't get this warning anymore. But i can't read the content. That is not a duplication.
Now i get this warning
Failed to load resource: the server responded with a status of 404 (Not Found)

Can you show us your REST api code so we can help you ? You need to set some headers in your backend to allow requests coming from other origins.
If you happen to be using express, this will help you. But you could have built the REST api in another way, so please provide us with more information.

This is because you are accessing a resource from another domain.
You try to access http://localhost:3000 from http://localhost:63342.
You can read more about this here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin

Basically you are performing a CORS request which means you are trying to call a resource on different server. So your REST api should allow CORS requests by adding the response headers allowing the UI server resource.
Please Refer to this question if it helps

Related

Get Header Request Javascript: cURL working, fetch forbidden

i want to GET Request the Header of this link https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8 in a React App. When doing a simple request
request('https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8', function (error, response, body) {
console.error('error:', error);
console.log('body:', body);
});
I get
Access to fetch at 'https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8' 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.
When using the cors-anywhere proxy
request('https://cors-anywhere.herokuapp.com/https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8', function (error, response, body) {
console.error('error:', error);
console.log('body:', body);
});
I get
request.js:150 GET https://cors-anywhere.herokuapp.com/https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8 403 (Forbidden)
But when I just cURL I get the right response
curl -s -o /dev/null -D - https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8
Can anyone explain this behaviour to me and maybe tell me how to overcome this?
Thanks!
CORS error usually comes up when you are trying to call an API from your browser directly and that API doesn't allow any other website to get the data.
There can be 2 workarounds to this problem I can think as of now -
Either you call that API from your backend code and you gather the data received from the website in backend and transfer the data on the client-side. Basically, you will be Wrapping the original API.
You can use Web Servers like NGINX and configure a specific path on the domain pointing to External API and other paths to your project. Which will help in making both the External API and Your React code on the same domain name.
Mainly your objective is to have that external API to work through your domain working along with your react code.
In browser context JS, such as a in a fetch call to an API, CORS applies. Rather with a CURL request, you are essentially running server side context, therefore CORS doesn't apply. This is why you can hit instagrams unofficial api from a server context or node.js context, but not from the same fetch call in a browser. Possible solutions:
Allow-Content-Orgin header set by the server must include the domain your page is hosted on.
Use Eletron or NodeWebkit.js for visual apps running client side with a browser (chromium) to launch your app in (mix of both browser and server context, CORS does not apply)
Run a node.js app (no browser, server context) and run your app from the terminal. (CORS does not apply)

Unable to show data to javascript after getScript() from API contain Json block database

I am new to Ajax/json/jquery so I have few questions. Currently, I'm having an API like https://example/api/1.1 which contain JSON block look similar to this
[{"id":"1","FirstName":"Micheal","LastName":"Kooling"},{"id":"2","FirstName":"Mike","LastName":"Kooling"}]
I tried to use XMLHttpRequest and AJAX to fetch the data but it gave me an error that I have been blocked by CORS: No 'Access-Control-Allow-Origin' header is present on the requested resource. And I have looked at a lot of article about it and nothing worked yet so if anyone can help me solve this?
So I tried another way using $(function(){ $.getScript('https://example/api/1.1');}); and this time the server response the data correctly but I do not know how to show the data from the API to script?
Can anyone explain me why the server respone and did not get blocked when I'm using getScript() function?
The API-Server has to be configured to accept your request. Otherwise it will block it and the client will throw the CORS error. The only way around this is to let your server request the API and then let the client make a request to your server, or to ask the owner of the server to enable CORS for your domain.
For further information look at the documentation: https://developer.mozilla.org/de/docs/Web/HTTP/CORS

What is the difference between getJSON() function and post() function when make a request across domain?

I am trying to access a Google Apps Script WebAPI from my website using javascript to pass some value and create an excel file and download it through this API.
I tried 2 following way:
Using POST request with $.post.
My values are many. So, at first, I use a POST request with a body is JSON of list values. Browser rejects API response, because of CORS error.
I researched about CORS to understand it. At some topics, I found a solution is the following second way.
Access to XMLHttpRequest at 'https://script.google.com/macros/s/xxxxxxx' from origin 'https://example.com' 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.
Using GET request with $.getJSON.
I pass JSON of list values to URL parameter and make GET request. It worked fine.
var url = 'https://script.google.com/macros/s/' + api_id + '/exec?' + request_parameter_string;
$.post(url, payload, function(data, textStatus) {
// Do something
}, 'json');
$.getJSON(url, function(json_result) {
// Do something
})
.fail(function() {
// Do something
});
What I do not understand is why? Why it works with getJSON but not work with post?
I think CORS work with both of GET and POST requests. And I checked the response header with Postman. The headers are the same Access-Control-Allow-Origin →*.
I think have something is different inside getJSON and post functions.
*UPDATE: Update POST CORS error message.
GET requests are not bound by CORS we can host images and static files in CDN which is different from the origin and would help in improving the performance by caching and making parallel requests.
Similarly GET is used for serving ads, trackers and analytics from third party domains as well.
More information about Same Origin Policy and GET is at https://security.stackexchange.com/a/16221/9517
How the browsers identify Other HTTP Verbs are allowed for the cross origin request is elaborated # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

How to handle CORS in a service account call to Google oAuth?

I access a Google calendar using a service account. This means that the owner of the calendar will not be prompted for his authorization.
This works fine in Python, where I make a requests call to https://accounts.google.com/o/oauth2/token with a specific body. This gets me back a token I can use later.
I now need to have an application running in a standalone browser (Chrome - without user interaction) and tried to directly port this call as
fetch('https://accounts.google.com/o/oauth2/token',
{
method: 'POST',
body: JSON.stringify(body),
})
.then(function(res) { return res.json(); })
.then(function(data) { alert(JSON.stringify(data)) })
but I get a reply from Google
Failed to load https://accounts.google.com/o/oauth2/token: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://devd.io' 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.
My limited understanding of CORS (a previous answer was a very good read) is that
No 'Access-Control-Allow-Origin' header is present on the requested
resource
means that it is not present in the response headers, which means that Google does not want me to access its resources via JS when ran from the browser (which points to something else that https://accounts.google.com).
This may be a good idea but I control all elements, from the code to the browser and would like to get that token the same way I get it in a non-browser environment, specifically my working Python code.
How can I tell https://accounts.google.com to send me back a Access-Control-Allow-Origin header which tell my browser that it is OK to accept the call?
You can't.
Client side and server side code need to interact with OAuth in different ways.
Google provide documentation explaining the client side process.
Importantly, part of it involves redirecting to Google's servers instead of accessing them with fetch or XMLHttpRequest.
#Quentin's answer "You can't" is the right one for my question ("how can I force the server to send back the right header").
This is a decision at Google not to provide this header, effectively cutting off any non-interactive applications.
As a solution, I will look at
how to force the browser not to take into account the security mechanisms provided by CORS (there seems to be some ways through extensions or command-line arguments, I will update this answer once I find it)
or write an intermediate layer which will query the data for me and pass them verbatim to the application (this is equivalent, in my case, of just making the query from JS - but it adds an extra layer of code and server)

No 'Access-Control-Allow-Origin' header is not present always shows no matter what url I try to use

I am trying to learn how to parse APIs using javascript and so I am trying to get some json through some get calls.
In my script I have
<script>
function foo() {
var request = window.superagent;
var url = 'http://www.google.ca';
request
.get(url, function(response) {
console.log(response);
})
.set('Accept', 'application/json');
}
foo();
</script>
No matter what url I use, I always get this error
XMLHttpRequest cannot load http://www.google.ca/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://server.com' is therefore not allowed access.
(index):22 Error: Origin is not allowed by Access-Control-Allow-Origin
at s.crossDomainError (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:7899)
at XMLHttpRequest.s.end.D.onreadystatechange (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:8551)
I tried using various example get request urls like wikipedia, nba stats, google etc...that work fine when I enter the url into my browser but it does not work when I try to use javascript to download the data.
I am using a local apache2 server on my ubuntu laptop. I am also using the superagent library for javascript, but i also tried using jquery and ajax and it's the same error.
so apparently I need to use a url that uses cors. The thing is
http://savvastjortjoglou.com/nba-shot-sharts.html?utm_source=Python+Weekly+Newsletter&utm_campaign=5185ff0538-Python_Weekly_Issue_202_July_30_2015&utm_medium=email&utm_term=0_9e26887fc5-5185ff0538-312727397
this tutorial just did a requests.get(url) which was the nba stats url and got his data. He did not get an error? How can I use a url that doesn't use cors to get data?
CORS is implemented on the browser end as well, to not allow javascript load malicious content from unknown sites. You should also try using the CORS plugin if you are still trying to scrap on the client side.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Categories