Convert GET curl to javascript fetch

I can successfully extract the object from the syntax using the following command:

curl -X GET \ -H "X-Parse-Application-Id:1231231231" \ -H "X-Parse-REST-API-Key: 131231231" \ -G \ --data-urlencode 'where={"uid":"12312312"}' \ https://api.parse.com/1/classes/birthday` 

But I'm trying to convert it to javascript using the code below, I will get a response with a status of 200 . I assume the error converts urlencode data to data:

 var getObject = function { var url = "https://api.parse.com"; url += '/1/classes/birthday'; fetch(url, { method: 'GET', headers: { 'Accept': 'application/json', 'X-Parse-Application-Id': '12122', 'X-Parse-REST-API-Key': '12121', 'Content-Type': 'application/json', }, data: '{"where":{"uid":"12312312"}}' }) .then(function(request, results) { console.log(request) console.log(results) }) } 

Thanks!

+6
source share
2 answers

Since I often wanted to do this, I did https://kigiri.imtqy.com/fetch/ , you can copy / paste the curl command, which will give you a sample code.

You can check the source if you want to use it differently.

+10
source

Okay, so basically you need another one then. So this is due to promises. I realized this after reading this wonderful article http://blog.gospodarets.com/fetch_in_action/

What you need to do is

 var getObject = function { var url = "https://api.parse.com"; url += '/1/classes/birthday'; return fetch(url, { method: 'GET', headers: { 'Accept': 'application/json', 'X-Parse-Application-Id': '12122', 'X-Parse-REST-API-Key': '12121', 'Content-Type': 'application/json', }, data: '{"where":{"uid":"12312312"}}' }) .then(function(response) { return response.text(); }) .then(function(data){ console.log(data); //this will just be text var data_obj = JSON.parse(data); return data_obj }) } 

I do not understand why you need to return response.text (). Again, this is something to do promises

https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise

Because when I access response.text () from the first, then. He returns the promise.

I hope some other kind gentleman can comment and explain why returning response.text () turns the promise into the data you need.

- EDIT -

I added a few returns to show how you can getObject to return the response data as an object. So,

 var d = getObject(); 

will return the response as a js object.

+3
source

Source: https://habr.com/ru/post/989704/


All Articles