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);
}
})
Related
I'm trying to pipe a request handling by a remote server, along with the following line:
Unfortunately pipe doesn't work well with post body, could you suggest how can I solve this issue?
self.downloadPriceLists = function (req, res, next) {
const options = {
url: `http://${env.MAILER_HOST}:${env.MAILER_PORT}/getpricelist/`,
method: 'POST',
json: true, // <--Very important!!!
headers: req.headers,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
},
body: {
userID: req.user.id,
exportAsOf: req.body.exportAsOf,
activationDate: req.body.activationDate,
},
};
console.log("options:", options);
// remoteResponse :: res
// remoteBody :: body
const myReq = request.post(options, function (error, remoteResponse, remoteBody) {
res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
remoteResponse.headers.hasOwnProperty('content-disposition') && res.setHeader('Content-disposition', remoteResponse.headers['content-disposition']);
remoteResponse.headers.hasOwnProperty('content-type') && res.setHeader('Content-type', remoteResponse.headers['content-type']);
if (error) {
console.error('request fail:', error);
return res.status(500).end('Error');
}
console.log('submit successful:', remoteResponse.headers);
res.pipe(remoteBody);
});
// Handle errors
myReq.on('error', function (err) {
console.log("++++++++++++sendReq Handle errors:", err);
res.status(500).end("Error:" + err);
});
};
Should you not be piping streams and not scalar data?
res.pipe(remoteBody); does look right to me, if anything, res.pipe(remoteResponse); seems more right.
Have you considered just writing the response of the inner request to the outer one without piping? Like so res.json(remoteBody); ?
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);
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'm trying attach an image using the bot emulator tool and sending this image off to the microsofts customvision api, the issue I'm having is that I get
{ Code: 'BadRequestImageFormat', Message: '' }
back from custom the custom vision api call.
I'm using the the request module from npm to handle the calls
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'xxx',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/octet-stream',
'Prediction-Key': 'xxx'
},
body: session.message.attachments[0]
}, function(error, response, body){
console.log(body);
});
}
});
I believe that I may be sending the wrong format through to custom vision however I have been unable to figure it out as of yet.
I replicated your issue and it looks like the problem is your 'Content-Type'. You're attempting to pass JSON in your request, but setting the content-type as octet-stream. See my modified code below:
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'https://northeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'Your API Key...'
},
body: session.message.attachments[0]
},
function (err, response, body) {
if (err) return console.log(err)
console.log(body);
});
}
});
When I run this, I get the error InvalidImageUrl which is to be expected as it's looking for a content on localhost. You could get round this by exposing your localhost using Ngrok.
I'm trying to get a response back from an API by sending the token and the header 'content-type': 'application/json', but I don't know where should I put them.
This is my code so far:
var request = require('request');
request.get('google example url', {
//
'auth': {
'bearer': '15252727282'
},
"headers": {
"Content-Type": "application/json"
}
}, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body);
});
This is what I'm getting back in my console:
error: null
statusCode: 401
body: HTTP Token: Access denied.
OK I did it using options as the first parameter and with the following lines:
const options = {
url: 'target url',
method: 'GET',
headers: {
"Authorization": "Token token=12425262",
"Content-type": "application/json"
}
};
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
});
You're getting that error because you have never defined require anywhere on your client-side.
Add this to your project: http://requirejs.org/docs/release/2.2.0/minified/require.js
If you want to use require on the client take a look at this http://requirejs.org/.