For a homework (in Signavio Workflow Accelerator) I need to add users to an organization on Github using the GitHub-API v3. The Code has to be written in JavaScript which i a language I'm not very familiar with.
At the moment I get the following error code: "SyntaxError: Unexpected token o in JSON at position 1 at Request._callback". So I have the feeling that there might be a problem with the parsing.
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
request({url: link, method: 'put', headers: {'User-Agent': 'request'}, auth: {username: token}, JSON: true},
function (response, body) {
console.log(body)
if(body !== undefined){
body = JSON.parse(body)
body['state'][0]['main']
status = body['main']['state']
status = body.main.state
}
else{
status = 'error'
}
})
I don't know if this might be helpful, but if I perform this put request using cURL it works and the answer starts with:
{
"url": "https://api.github.com/orgs/myorganization/memberships/githubUser",
"state": "pending",
...}
So this "state" is the value I want to read in the code above.
Already thanks for helping!
I worked together with a friend of mine and together we found a working solution. So if anyone else is having the same struggle: This piece of code does the magic!
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
const options = {
url: link,
method: 'put',
headers: {'User-Agent': 'request'}, auth: {username: token}
}
function callback(error, response, body) {
console.log(error)
if(!error && response.statusCode == 200){
const info = JSON.parse(body)
status = info['state'][0]['main']
console.log(status)
status = info['state']
status = info.state
}
console.log(body)
}
request(options, callback)
Related
I'm trying to log into a loopback API I'm running on a web server using the standard POST login request. However every time I run it I get:
{"error":{"statusCode":400,"name":"Error","message":"username or email is required","code":"USERNAME_EMAIL_REQUIRED"}}
I've tried logging in two ways. firstly:
var userDetails = {
"email": "foo%40bar.com",
"password": "test"
}
const requestOptions = {
url: "APIURL/api/Users/login?email="+userDetails.email+"&password="+userDetails.password
};
request.post(requestOptions, function (error, response, body) {
console.log(body);
});
And:
var userDetails = {
"email": "foo%40bar.com",
"password": "test"
}
const requestOptions = {
url: "https://temp-243314.appspot.com/api/Users/login",
header: {
"email": userDetails.email,
"password": userDetails.password
}
};
request.post(requestOptions, function (error, response, body) {
console.log(body);
});
Where both return the same error.
I like it when I see ; at the end of declarations :/. your var declarations need a lil ; :D
I'm 99% sure they are going to want that in the body. Those headers that you show in your 2nd attempt are non-standard so they would be stripped from most inbound servers (As is standard for most ingest servers like NGINX) If they wanted a custom header, they probably would have noted it like, "X-email" or something weird.
IF you're going to send those elements in the "body", they probably want it in JSON format, in which case you need to designate json=true in the request function.
If sent in the body, don't url encode with the %40 in replacement of the #
5.
const request = require('request');
let options = {
uri: 'APIURL/api/Users/login',
method: 'POST',
json: {
"email":"foo#bar.com",
"password":"¡¡¡¡¡¡¡¡UNHACKABLE!!!!!!!!!"
}
};
request(options, function (err, resp, body) {
let isHTTPSuccess;
try {
isHTTPSuccess = resp.statusCode + '';
isHTTPSuccess = isHTTPSuccess[0];
if (isHTTPSuccess === '2'){
isHTTPSuccess = true;
} else {
isHTTPSuccess = false;
}
} catch(parseError){
console.error(parseError);
console.error(err);
return;
}
if (err || !isHTTPSuccess){
console.error(body);
return;
}
console.log('WOWZER, THE CODE ABOVE IS A BIT MUCH NO? ANYWAY... HERE IS THE BODY: ', body);
return;
});
Good Luck!
Your request should be like:
var userDetails = {
"email": "foo#bar.com",
"password": "test"
}
I want to pass the value in API request body.
I tried below code for that
var options = { method: 'POST',
url: 'https://ssgpreprod.serviceurl.in/gonogo-api/atm/tw/cro-approval',
headers:
{ 'Postman-Token': '9d6a0ad1-c3a1-402f-b845-b6416f49df6b',
'cache-control': 'no-cache',
'Content-Type': 'application/json' },
body:
{ oHeader:
{ sReqType: 'application/json',
sAppSource: 'WEB 2.02.01',
sSourceID: 'GONOGO_HDBFS',
sAppID: 610961419000670,
dtSubmit: '',
sCroId: 'HDB_TW_CRO#cell.com',
sDsaId: 'default',
sInstID: 4019,
sUserName: 'CHDBTWCRO',
sProduct: 'TW',
sDealerId: '61096' },
sRefID:testData.twPreIpa.twReferenceId,
sAppStat: testData.twCroDetails.twCroDecision,
aCroJustification: [ { sRemark: testData.twCroDetails.twRemark, sSubTo: testData.twCroDetails.twSubjectTo} ],
bApprAmtExist: true,
dApprAmt: testData.twApplyDetails.twLoanAmount,
dItrRt: testData.twCroDetails.twRoi,
dLtv: testData.twCroDetails.twLtv,
aDedupeRefID: [] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
browser.logger.info(JSON.stringify(body));
browser.logger.info(JSON.stringify(response));
browser.logger.info('status code is : ' + response.statusCode);
expect(response.statusCode).toBe(200).then(function () {
browser.logger.info('case is approved');
this.logOut(testData);
})
});
I am passing value from xlsx file i.e testData.twPreIpa.twReferenceId but I am getting 422 status code and below output
[2019-05-28 15:42:10.403] [INFO] : - {"title":"Conversion Failed","status":422,"detail":"The content you've sent is probably malformed."}
Also, when I add - browser.logger.info('approved'); above var options it prints on console.. but when I add - browser.logger.info(testData.twPreIpa.twReferenceId);
It gives me error .. ouput displayed -
Failed: Cannot read property 'twReferenceId' of undefined
TypeError: Cannot read property 'twReferenceId' of undefined
While this may not directly answer your question it should be helpful to you.
I worked on a similar framework to what (I assume) yours looks like,some api and some UI validations.
I had a separate class for my API calls which returned some value, sometimes the entire response body. I allowed myself the ability to pass in whatever body I needed as a parameter.
This is an example of the approach I took.
module.exports = class Endpoints {
addSomethingToUser(bearerToken, userId, JSONbody) {
//Function will preform a POST request and return the status code if successful
//Else if will return the body of the response
let endpoint = 'http://myApp.com:9090/api/users/' + userId;
return new Promise((resolve, reject) => {
let options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(JSONbody),
};
request(
endpoint,
options ,
function (error, response, body) {
if (!error && (response.statusCode >= 200 && response.statusCode < 300)) {
resolve(response.statusCode);
} else {
console.log('error:', error, response && response.statusCode);
reject(JSON.stringify(response, undefined, 2));
};
}
);
});
};
}
It is called like
let apiCallsFile = require('../apiCalls/restCalls');
let apiCalls = new apiCallsFile();
it('simple test', async function(){
let requiredBody = {
"NAME": "Test Name",
"GENDER": "MALE",
};
let apiResult = await apiCalls.addSomethingToUser(bearerToken, userId, requiredBody );
expect(apiResult).toBe('201');
}
Your issue seems to be related to the actual values you are using from excel. You should attempt to print out your values before attempting to send the request to ensure they are all present and in the format you expect.
Spent a few hours trying to solve this but keep on getting 400 errors. I think my payload is incorrect but not sure what I need to do.
I've tried the same request in POSTMAN with great success, and also have tried different combinations on formatting my payload (body).
I've also tried the following: var body = {"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}};
function main(){
// Set the headers
var headers = {
'Authorization': 'Bearer ya29.GlyvBPhT4Y502Yo4NZ6sKI001AYlVU6om5ytXrzf2vjfEYERrsdMSBu-2ZkKir83jjj06-ewqYuBvvrx8mKfuTW1YjjlmtPmRdlK0I0Gjx',
'Content-Type': 'application/json',
'User-Agent': 'Untitled browser'
}
var uri = 'https://language.googleapis.com/v1/documents'+encodeURI(':analyzeSentiment');
var form = JSON.stringify({"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}});
// Configure the request
var options = {
url: uri,
method: 'POST',
headers: headers,
form: form
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
else{
console.log('Error code: '+response.statusCode)
}
})
}
main();
Update - this is how it works in POSTMAN
Header is the same too:
Solved!
Need to post as body rather than form
Im trying to send a post request to an arduino with Node JS and the Request package:
var body = {
d:"5",
l:"6",
TOTAL_VOLUME: "75",
meterId: "9"
};
var options = {
url: 'http://'+'192.168.1.102'+'/configData',
timeout: 7000,
headers: {
'Content-type' : 'application/json',
'Content-length': JSON.stringify(body).length
},
json:true,
body: JSON.stringify(body)
};
request.post(options, function (error, response, body) {
//console.log(error);
//console.log(response);
console.log(body);
if (!error && response.statusCode == 200) {
console.log("Changed configuration succesfully. ");
// Request to enpoint to save changes in database
var options = {
url: 'http://'+'8.8.8.8:4000'+'/meter/'+meter.id+'/',
method: 'PUT',
timeout: 10000,
body: {
'tank_diameter': tank_diameter,
'tank_length':tank_length,
'tank_capacity': tank_capacity
}
};
/*request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
}
});*/
}
done();
}).on('error', function(err) {
console.log(err);
done();
});
The above code is how I send the data, However Im not able to get the data on the arduino.
This is the code on arduino:
server.on("/configData", HTTP_POST, [](){ // configData Seteo de Valores desde POST
StaticJsonBuffer<200> configBuffer;
JsonObject& configJson= configBuffer.parseObject(server.arg("plain"));
String l = configJson["l"];
String d = configJson["d"];
String meterId2 = configJson["meterId"];
String volumenTotal = configJson["TOTAL_VOLUME"];
LENGTH = l.toFloat();
HEIGHT = d.toFloat();
meterId = meterId2.toInt();
TOTAL_VOLUME = volumenTotal.toFloat();
// GUARDAR EN LA EEPROM
int EEadr = 0;
EEPROM.write(EEadr, HEIGHT);
EEPROM.commit();
EEadr = 10;
EEPROM.write(EEadr, LENGTH);
EEPROM.commit();
EEadr = 20;
EEPROM.write(EEadr, TOTAL_VOLUME);
EEPROM.commit();
EEadr = 30;
EEPROM.write(EEadr, meterId);
EEPROM.commit();
//SHOW ON SERIAL MONITOR
Serial.println("l= "+l);
Serial.println("d= "+d);
Serial.println("meterId2= "+meterId2);
Serial.println("TOTAL_VOLUME= "+volumenTotal);
server.send ( 200, "text/json", "{success:true}" );
});
The weird thing is that if I use curl like this:
curl -H "Content-type: application/json" -X POST -d "{l:\"55\", r:\"10\", meterId: \"2\"}" http://192.168.1.2
The arduino does receive the data correctly, so the problem is most likely on my Node JS request. Can anyone tell me what Im I doing wrong here?
UPDATE:
Ive checked the requests with wireshark, and it results that the curl request (the one that is working) is being sent as Line based text data. Can anyone tell me how can I send it the same way using Node JS and request?
In these type of situations you can check your request structure with applications like wireshark.
In this problem if you can see that you attach your hole json as a single string, because when you set json flag of request in request library it convert your body into json for you so now you have something like:
var options = {
body: JSON.stringfy(JSON.stringfy(body))
};
so you can correct your application by simply set following options:
var options = {
url: 'http://'+'www.goole.com'+'/configData',
timeout: 7000,
json:true,
body: body
};
I cannot figure out how to get a variable from a node.js module. I'm creating a module that will interface with an authentication mechanism, and currently it only returns a token. I need this token in the main.js, as I will be calling other modules, and passing this token for authentication.
//auth.js
var request = require("request");
var authModule = {};
var authToken = "";
var options = {
method: 'POST',
url: 'https://dummy.url/oauth/token',
headers: {
'authorization': 'Basic secretkeystring',
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'password',
username: 'indegomontoya',
password: 'sixfingeredman'
}
};
authModule.getToken = function getToken(){
request(options, requestToken);
};
function requestToken (error, response, body) {
if (error) throw new Error(error);
authToken = response.body.toString().split('\n')[1].split(":")[1].split('"')[1];
console.log("auth.js says: " + authToken);
// ^^ this works, and spits out the correct token to the console
return authToken;
};
module.exports = authModule;
module.exports.token = authToken;
And here is my main.js:
//main.js
var auth = require("./auth.js");
var token;
token = auth.getToken();
console.log("main.js says :"+ token);
// ^^ comes back undefined
I've seen examples of sending a variable from main.js to module.js, but I need to do the opposite. Any help is greatly appreciated!
EDIT: typo in code.
Try passing a hash instead.
module.exports = {
module: authModule,
token: authToken
}
var gcdm = require("./gcdm.js");
gcdm.module();
gcdm.token;
It appears that the request module (from here), is asynchronous in nature, meaning that it can take any length of time to return its data. This means that you may need to use a callback when using the getToken method.
Currently, your main.js app does not give suffiecient time for the auth.js module to fetch the token data. It requests the token and then in the same breath (or tick of the processor) it tries to print it to the console. To get around this problem, you need to utilise callbacks.
I would probably adjust your two auth module methods like so:
authModule.getToken = function getToken(callback){
request(options, function(error, response, body){
if (error) throw new Error(error);
callback( requestToken(body) );
});
};
function requestToken (body) {
authToken = response.body.toString().split('\n')[1].split(":")[1].split('"')[1];
return authToken;
};
Also, remove this uneeded line, as your callback will be the delivery mechanism back to your main app:
module.exports.token = authToken; // remove this
You would then use something like this to get the token in your main app:
gcdm.getToken( function (token) {
console.log('main.js says :' + token);
});
You may want to look a bit more into Asynchronous Programming in JavaScript. It's a key ingredient in the NodeJS toolbox.
#shennan thank you very much! You were right on track, and you are correct, request is async. I'm fairly new to node.js, so thanks for bearing with me, and am still trying to wrap my head around callbacks. (thanks #Drazisil for your link to callbackhell.com)
Your answers got me int he right direction, and I ended up with this:
//auth.js
var request = require("request");
var authModule = function () {};
var authToken = "";
var options = {
method: 'POST',
url: 'https://dummy.url/oauth/token',
headers: {
'authorization': 'Basic secretkeystring',
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'password',
username: 'indegomontoya',
password: 'sixfingeredman'
}
};
authModule.getToken = function getToken(callback){
request(options, function(error, response, body){
if (error) throw new Error(error);
authToken = response.body;
callback( requestToken(body) );
});
};
function requestToken (body) {
return authToken;
};
module.exports = authModule;
And:
//main.js
var auth = require("./auth.js");
var authTokenData;
function parseAuthJson(data) {
var jsonData = JSON.parse(data);
return jsonData;
}
auth.getToken( function (authTokenData) {
var jsonData = parseAuthJson(authTokenData);
console.log(jsonData.access_token);
});
I gathered help about parsing the JSON here.
Thanks for your help!