The goal I want to achieve is to read and later write issues and labels within a github repository using javascript.
So far I have been able to get authenticated and retrieve some data on the repository, but I do not find the way to retrieve data neither on one single, nor on a set of issues.
This is the code I am using.
var request = require("request");
var url = 'https://api.github.com/graphql';
var headers = {
Authorization:'token XXXXXXXXXXXXXXXXXXXXXXXXXXX',
Accept: 'application/json',
'User-Agent': 'request',
'Content-Type': 'application/json'
};
var options = {
method: 'post',
body: undefined,
json: true,
url: url,
headers: headers
};
function makeRequest(options){
request(options, function (error, response, body) {
if (error) {
console.error('error posting json: ', error);
throw error;
}
var responseHeaders = response.headers;
var statusCode = response.statusCode;
console.log('Status code: ', statusCode);
console.log('Body: ', body);
});
};
options.body = {
query: '{repository(owner:"TonyEdelweiss", name:"hello-world") {createdAt name projectsUrl}}'
};
makeRequest(options);
options.body = {
query: '{repository(owner:"TonyEdelweiss", name:"hello-world"){issues(first: 2){edges{cursor node{id}}}}}'
};
makeRequest(options);
On the first makeRequest() I get the following, which is okay:
Status code: 200 Body: { data: { repository:
{ createdAt: '2017-09-29T17:01:25Z',
name: 'hello-world',
projectsUrl: 'https://github.com/TonyEdelweiss/hello-world/projects' } } }
On te second one I only get an '[Object]' )-:
Status code: 200 Body: { data: { repository: { issues: [Object] } }
}
Can anybody give a hint?
Also I have found this in github API v4 documentation: "All GraphQL operations must specify their selections down to fields which return scalar values to ensure an unambiguously shaped response." This might explain why I am not getting the data, but gives no further guidance.
Your request is actually working fine. But the maximum depth you can view using console.log default to 2. You can use util.inspect to change it, set the depth to null to view the full object :
const util = require('util');
.....
console.log('Body: ', util.inspect(body, {depth: null}));
Related
Actually am kinda disappointed as I tried many things and checked out many articles but non worked out for me.
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://***********.com/connect/api.php?action=2&token="+tokenV;
const myHeaders = new Headers();
const myRequest = new Request(urlF, {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default',
});
fetch(myRequest)
.then(response => response.json())
.then(data => console.log(data));
}
I have already whitlist the domain inside my config file, am using phonegap CL latest version. I'm trying to connect to an api which will out put json.encode data if token were right.
Error output:
(index):50 Fetch failed loading: GET https://*******.com/connect/api.php.............
Another way I tried using cordova fetch plugin still failed:
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://*********.com/api.php?action=2&token="+tokenV;
console.log("nowww1");
cordovaFetch(urlF, {
method : 'GET',
headers: {
'User-Agent': 'CordovaFetch 1.0.0'
},
})
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
Error out put:
Error: exec proxy not found for :: FetchPlugin :: fetch (index):118 parsing failed TypeError: Network request failed
I can change the out put as I want but show me away to get the data from an external server???
Thank you
I am trying to integrate coinmarketcap api but cannot really get the data. I registered, got the API key, and wrote the following method to fetch the data:
let getPostsList = async () => {
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
mode: 'no-cors'
};
try {
const response = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
const json = await response.body;
// console.log(json)
return json
} catch (err) {
console.log('Error: ', err)
}
};
All I get is 401 error, like this:
GET https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
401
Any suggestions what I should fix? Docs says that 401 is likely connected to API key, but they say to provide it in the headers like the above...
From what I've tested after getting my own API key, the no-cors mode is problematic. You will need to use CORS, where https://cors-anywhere.herokuapp.com/ comes into handy.
Just send the request like this :
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.
API returns the following:
{
data: [
{
type: "aaa",
name: "Cycle",
id: "c949up9c",
category: ["A","B"]
},
{
type: "bbb",
name: "mobile",
id: "c2rt4Jtu",
category: ["C","D"]
},
...
]
}
server.js
function sortDataByID(data) {
return data.filter(function(item) {
return item.id == 'c949up9c';
});
}
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options).pipe(sortDataByID(res));
});
I keep getting the following error message.
TypeError: data.filter is not a function
What is the obvious mistake here? Anyone?
I think your mistake is to think than res is the data than you expect.
But if you take a look inside res you should find the data.
so you must get datafrom the res and use it.
For example:
const data = res.data;
request.get(options).pipe(sortDataByID(data))
Have a nice day !
I've personally never seen piping to a function. I don't think that should work. In any case:
You can use a callback instead of piping. Try this:
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
json: true, //little convenience flag to set the requisite JSON headers
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options, sortDataByID);
});
function sortDataByID(err, response, data){ //the callback must take 3 parameters
if(err){
return res.json(err); //make sure there was no error
}
if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
return res.status(400).json(err)
}
let dataToReturn = data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
return item.id == 'c949up9c';
}
res.json(dataToReturn);
}
I received TypeError: data.filter is not a function while doing Unit testing.
I was passing an object not an array in the result.
gateIn$: of({}),
instead of
gateIn$: of([]),
gateIn$.pipe(takeUntil(this.destroy$)).subscribe(bookings => (this.dataSource.data = bookings));
once you see the error it is pretty obvious, the hard bit is spotting it in the first place.
I want to call to API, get json data and set it to resolvers Query in Graphql. So far I managed to working Graphql server and get call to API. This is my code so far
//resolvers.js
//var fetch = require('node-fetch');
var request = require("request");
var options = { method: 'GET',
url: 'http://mydomain.con/index.php/rest/V1/products/24-MB01',
headers:
{ 'postman-token': 'mytoken',
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: 'Bearer mytoken' } };
const links = request(options, function (error, response, body) {
if (error) throw new Error(error);
//body = json data
//console.log(body);
});
module.exports = {
Query: {
//set data to Query
allLinks: () => links,
},
};
I dont know how to set the body parameter which contain json data to Query. I have also same data on "http://localhost/src/apicall.php" but this is not working with node-fetch (or Im making mistakes). Api is from magento2.
You were close !
What you are doing right now is sending the links request right when your application starts. You don't want that ; you want to send the request when the allLinks field is requested in GraphQL.
So what you need is to have in the allLinks field a function making the request to your API, and returning the response.
If you return a Promise within the allLinks field, it will wait upon completion to use the returned value as an answer.
So, putting it all together:
...
const getAllLinks = () => {
return new Promise((resolve, reject) => {
request(options, function (error, response, body) {
if (error) reject(error);
else resolve(body);
});
});
};
module.exports = {
Query: {
//set data to Query
allLinks: getAllLinks,
},
};
I'm calling the Firebase REST API from a Node.js process. The problem I'm seeing is that POSTS fail when the post body contains non-ASCII characters. This is despite the request returning a "200" status, and the name of a node (which doesn't actually get created).
I'm currently trying something like this:
function push(path, object, callback) {
console.log("Pushing to "+path+" on: "+firebase.host);
var fullPath=firebase.basePath+path;
console.log("fullPath="+fullPath);
var body = JSON.stringify(object);
var options = {
host: firebase.host,
port: 80,
method: "POST",
path: fullPath, //gamma.firebase.com/...
agent: false,
headers: {
'content-type': 'application/json',
'Content-Length': body.length,
}
};
var req = http.request(options, function(response) {
var result = "";
console.dir(response.headers);
response.on('data', function(chunk) {
result+=chunk;
});
response.on('end', function() {
console.error("POST response result: "+result);
try {
callback(JSON.parse(result));
} catch(e) {
callback({ error: e });
}
});
response.on('error', function(e) {
console.error("POST response error: "+error);
callback({error: e});
});
});
req.on('error', function(error) {
console.error("POST request error: "+error);
});
req.write(body);
req.end();
}
The contents of "object" can be as simple as:
{"text": "test\u00a0text"}
The result I get back is status 200, and an reasonable-looking child name, which doesn't actually get created.
I've tried setting content-type to a bunch of different things (adding ; charset="UTF-8", for example), and it doesn't seem to affect the results at all.
There is an error in the way we are handling certain types of input which is yielding the erroneous 200 status. We will roll out a fix shortly. To work around the problem in the meantime you can omit sending the Content-Length header. This will allow you to post ASCII and non-ASCII data.