I would like to access the content of a file I uploaded to GitHub via Node.js.
The GitHub repository is private, so I have generated an access token at https://github.com/settings/tokens
Unfortunately, I keep getting a 404 – Not found error. What am I doing wrong?
const request = require('request');
const URL = 'https://raw.githubusercontent.com/myuser/myrepo/master/myfile.js';
const TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var options = {
url: URL,
headers: {
'Authorization': TOKEN
}
};
function callback(error, response, body) {
console.log(response.statusCode);
console.error(error);
console.log(body);
}
request(options, callback);
Thanks to the comment of #bhavesh27 I figured, I was missing a "token " in my header.
const request = require('request');
const URL = 'https://raw.githubusercontent.com/myuser/myrepo/master/myfile.js';
const TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var options = {
url: URL,
headers: {
'Authorization': 'token ' + TOKEN
}
};
function callback(error, response, body) {
console.log(response.statusCode);
console.error(error);
console.log(body);
}
request(options, callback);
Related
I am trying to do query to find a account using rest services of the target application name hexion.
When I am running it is giving Invalid uri error.
The url that I tested in postman is like below
https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts?q=OrganizationName = Hexion
and in postman I am getting response too.
But I feel somewhere in my code I am doing some syntax error but not able to find that
//nodejs v4.2.6
console.log("Hello, World!");
var Request = require("request");
var serviceUserName="msonawane#gmail.com";
var password="Welcome01";
var personalDataURL="https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts";
var option1 = {
uri: personalDataURL,
qs: {
q:{OrganizationName:"Hexion"}
},
headers: {
"Authorization" : auth,
"Content-Type": 'application/json',
"Accept":'application/json'
}
};
var auth = `Basic ` + new Buffer(serviceUserName+`:`+password).toString(`base64`);
Request.get(option1, { json: true },
(error, response, body) => {
console.log(response);
//console.log(response.url);
if (error) { return console.log(body,error); }
console.log(body.url);
console.log(body.explanation);
});
I expect it to return response after successful get
Please let me know error, I have changed the auth credentials so once you find anything to be corrected let me for the above code, I will try with right credentials and update you
request.get method expects first parameter as url, but you are passing options1 obj, it couldn't find url hence it is giving error "Invalid uri /".
You can append query parameter to url OR use querystring npm
var personalDataURL= "https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts?q=OrganizationName=Hexion"
request({
headers: {
"Authorization" : auth,
"Content-Type": 'application/json',
"Accept":'application/json'
},
uri: personalDataURL,
method: 'GET'
}, function (err, res, body) {
//it works!
});
For more details, refer request
I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?
Below is how i call speech api by node.js.
'use strict';
const request = require('request');
const subscriptionKey = 'MYSUBSCRIPTIONKEY';
const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
const options = {
uri: uriBase,
body: 'speech.wav',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey,
'Transfer-Encoding': 'chunked',
'Expect': '100-continue',
'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
You can try this
fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
if (err) throw err;
var options = {
host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
method: 'POST',
headers: { 'Content-Type': 'audio/wav' }
};
var req = http.request(options, function(res) {
// Handle a successful response here...
});
req.on('error', function(e) {
// Handle an error response here...
});
// Write the audio data in the request body.
req.write(data);
req.end();
});
I've figured out how to read values from a Budgeting Spreadsheet I created, but I can't figure out how to create a new spreadsheet with the Sheets API V4. I've been struggling with this problem for 5 months by now, has anyone solved this problem before?
Here's my code:
// READ - WORKING!
router.get("/get", (req, res) => {
var id = '1LoSF_4Z9aoiVvDsjFV9CMOd--vvz3fERfOPajVb2sv8';
var params = 'https://sheets.googleapis.com/v4/spreadsheets/?key='
var url = params + apiKey;
request(`https://sheets.googleapis.com/v4/spreadsheets/${id}?key=${apiKey}`, (error, response, body) => {
console.log("Body", body);
});
})
// Create - NOT WORKING!
router.post('/create', (req,res)=>{
request({
method: 'POST',
uri: `https://sheets.googleapis.com/v4/spreadsheets?fields=properties%2Ftitle&key=${apiKey}`
}, (error, response, body)=>{
console.log(body);
//Logs the body of the newly created spreadsheet
})
})
I used the guidelines from Google's API Explorer, you can find it here:
https://developers.google.com/apis-explorer/#p/sheets/v4/sheets.spreadsheets.create
Thank you!
How about this modification?
Modification points:
Add headers using the access token.
Add body for giving the title of created spreadsheet.
Modified script:
request({
method: 'POST',
uri: 'https://sheets.googleapis.com/v4/spreadsheets?fields=properties%2Ftitle%2CspreadsheetId',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
body: JSON.stringify({properties: {title: "sampleTitle"}}),
}, (error, response, body) => {
console.log(body);
});
Note:
When you use this script, please use the access token including https://www.googleapis.com/auth/spreadsheets to the scopes. This scope is used to create the spreadsheet.
Reference:
spreadsheets.create
I actually got it to work! Similar to the previous response (thank you Tanaike!!!).
request({
method: 'POST',
url: 'https://sheets.googleapis.com/v4/spreadsheets',
headers:{
'Authorization': 'Bearer (access token goes here)'
},
body: JSON.stringify({
properties: {
title: "Spreadsheet Title Goes Here"
}
})}, (error, response, body)=>{
if(!error && response.statusCode == 200){
var info = JSON.parse(body);
console.log(info);
} else {
console.log(error);
}
})
I'm trying to receive my users that are stored in Auth0. So, I tried using this website Auth0 management API docs with my API token and API domain. This works fine!
Then I tried to do the same in node js, but when I do that it returns an error. The error message is:
"statusCode":400,"error":"Bad Request","message":"Bad HTTP authentication header format","errorCode":"Bearer"
This is the code that i fount in the documentation
var request = require("request");
var options = { method: 'GET',
url: 'https://<api_url>/api/v2/users',
headers: { authorization: 'Bearer ACCESS_TOKEN' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The only thing that is changed is that I deleted the query string and inserted my api_url and the same access token that I used on the Auth0 management API docs (which works). Am I missing something?
The code looks perfectly fine. I edited it with my hostname/access token as follows and it returned the users:
var request = require("request");
var token = 'eyJ0...'
var options = { method: 'GET',
url: 'https://tenant_name.auth0.com/api/v2/users',
headers: { authorization: 'Bearer ' + token }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The two things that might have gone wrong in your case are:
You didn't properly replace the ACCESS_TOKEN in the code.
The access token does not have the read:users permission. You can verify this by pasting the token in jwt.io and inspecting the payload.
I'm trying to scrape a web-page for some data and I managed to post a request and got the right data. The problem is that I get something like :
"Kannst du bitte noch einmal ... erzýhlen, wie du wýhrend der Safari einen Lýwen verjagt hast?"
normally erzählen - während, so Ä,Ö,ß,Ü are not showing correctly.
here is my code:
var querystring = require('querystring');
var iconv = require('iconv-lite')
var request = require('request');
var fs = require('fs');
var writer = fs.createWriteStream('outputBodyutf8String.html');
var form = {
id:'2974',
opt1:'',
opt2:'30',
ref:'A1',
tid:'157',
tid2:'',
fnum:'2'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
var utf8String = iconv.decode(body,"ISO-8859-1");
console.log(utf8String);
writer.write(utf8String);
});
how to get the HTML body in with the correct letters?
How do I find out the correct encoding of a response?
I went to the website you are attempting to scrape, and found this:
And another character encoding declaration here:
This website defined two different charater encodings! Which do I use?
Well, this doesn't apply to you.
When reading an HTML file from a local machine, then the charset or content-type defined in the meta tags will be used for encoding.
Since you are retrieving this document, over HTTP, the files will be encoded according to the response header.
Here's the reponse header I received after visiting the website.
As you can see, they don't have a defined character set. It should be located in the Content-Type property. Like this:
Since they don't have any indicated charset in the response header, then, according to this post, it should use the meta declaration.
But wait, there was two meta charset declarations.
Since the compiler reads the file top to bottom, the second declared charset should be used.
Conclusion: They use UTF-8
Also, I don't think you need the conversion. I may be wrong, but you should just be able to access the response.
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
console.log(body);
writer.write(body);
});
Edit: I don't believe the error is on their side. I believe it's on your side. Give this a try:
Remove the writer:
var writer = fs.createWriteStream('outputBodyutf8String.html');
And in the request callback, replace everything with this:
function (err, res, body) {
console.log(body);
fs.writeFile('outputBodyutf8String.html', body, 'utf8', function(error) {
if(error)
console.log('Error Occured', error);
);
}
All the code should look like this:
var querystring = require('querystring');
var iconv = require('iconv-lite')
var request = require('request');
var fs = require('fs');
var form = {
id:'2974',
opt1:'',
opt2:'30',
ref:'A1',
tid:'157',
tid2:'',
fnum:'2'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
console.log(body);
fs.writeFile('outputBodyutf8String.html', body, 'utf8', function(error) {
if(error)
console.log('Error Occured', error);
);
}