Failing to log into loopback API using request - javascript

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"
}

Related

how to convert nested object to querystring in node using http module

I need help to send a nested object on the POST request to stripe API using standard http module on node.js
When I use querystring module to convert the json to a querystring it does not give appropriate output.
It does not behave well with a nested object.
This is my payload object:
const payload = {
"card": {
"number": number,
"exp_month": exp_month,
"exp_year": exp_year,
'cvc': cvc
},
};
My helper method to send HTTP POST request:
helpers.createPaymentToken = (payload, callback) => {
//validate the parameters
if (payload) { //configure the request details
const stringPayload =queryString.stringify(payload)
//configure request details
const requestDetails = {
protocol: "https:",
hostname: "api.stripe.com",
method: "post",
path:
"/v1/tokens",
auth:config.stripe.authToken,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(stringPayload),
},
};
//instantiate the request
const req = https.request(requestDetails, function (res) {
res.setEncoding('utf8');
var body = '';
console.log(res)
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode != 200) {
callback(res.statusCode,body);
} else {
callback(null);
}
});
});
//bind to an error event so it does not get thrown
req.on("error", (e) => {
callback(e);
});
//Add the payload
req.write(stringPayload);
//end the request
req.end();
} else {
callback("Given parameters are missing on invalid");
}
};
expected querystring:
card[number]=****************2&card[exp_month]=11&card[exp_year]=2021&card[cvc]=***
expected output:(request body)
{
"card": {
"number": "************4242",
"exp_month": "11",
"exp_year": "2021",
"cvc": "***"
}
}
actual output: (request body)
{
"card": ""
}
Your code is currently handling card details directly which you shouldn't attempt for security reasons.
Since you are collecting card details, you should use Elements which is Stripe's UI library to collect card details client-side securely while meeting the lowest level of PCI compliance. You can read more about PCI compliance here.

MailChimp Error Status: 401 Title: "API Key Invalid"

I am following a MailChimp API tutorial
When I test the API, I get a 401 response saying my API key is invalid.
Error -
Status: 401
"Your API key may be invalid, or you've attempted to access the wrong datacenter."
I have yet to register a domain yet, this is being testing using a local server. Could this be error be caused by MailChimp's refusing the request for another reason, perhaps CORS?
app.post('/signup', (req, res) => {
// Get form data
const { email } = req.body;
// Make sure field is filled
if(!email) {
res.redirect('/html/fail.html');
return;
}
// Construct req data
const data = {
members: [
{
email_address: email,
status: 'subscribed'
}
]
}
// Convert to JSON
const postData = JSON.stringify(data);
const options = {
url: 'https://us19.api.mailchimp.com/3.0/lists/listID',
method: 'POST',
headers: {
Authorization: 'auth xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us19'
},
body: postData
};
request(options, (err, response, body) => {
if(err) {
console.log(err);
res.redirect('/html/fail.html');
} else {
if(response.statusCode === 200) {
res.redirect('/html/success.html');
} else {
console.log(response.body);
res.redirect('/html/fail.html');
}
}
});
})
I tried running the same code in request in PostMan and I got back a 200 response.
I was initially importing the API key from a config file, that I had not destructured...

API json data to javascript variables

I have this problem, i have been trying 2 days to solve it.
My Javascript code:
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.stringify(JSON.parse(body), null, 4));
}
I want to get the data what the api sends back, into variables or somekind of thing, so i can call them anywhere in the script. The json data what comes back:
{
"data": {
"stop": {
"stoptimesWithoutPatterns": [
{
"realtimeArrival": 60065,
"scheduledArrival": 60000,
"realtime": true,
"serviceDay": 1547676000,
"headsign": "Olympiaterminaali via Kallio"
}
]
}
}
}
but when i use something about like this;
let stoptimesWithoutPatterns = body['stop'].stoptimesWithoutPatterns
it gives me error as
TypeError: Cannot read property 'stoptimesWithoutPatterns' of undefined
As im very new to coding coding, i dont know very tehnical stuff. It would be cool if somebody could help me :) as i wanted to have my own website or app based around this if i can get this to work! Thank you!
By using this i accomplished what i wanted, thank you guys who commented! :) This gives me the value of realtimeArrival! :)
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(JSON.parse(body));
//console.log(JSON.stringify(JSON.parse(body), null, 4));
let Parsed = JSON.parse(body);
let stoptimesWithoutPatterns = Parsed.data.stop.stoptimesWithoutPatterns[0]['realtimeArrival'];
console.log(stoptimesWithoutPatterns)
}
});

Problem with Github-Api v3 using JavaScript

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)

How to handle multi-page requests to Github API with Node.js Request module?

I'm trying to access all repositories that have more than 5000 stars on Github. I've written this scraper to work with Node.js (it's running on a Cloud9 environment):
var request = require('request');
var fs = require('fs');
var options = {
url: 'https://api.github.com/repositories',
headers: {
'User-Agent': 'myusernamehere'
},
qs: {
stargazers: 5000
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.headers);
fs.writeFile('output_teste.json', body, function (err) {
if (err) throw err;
console.log('It\'s saved!');
console.log(response.statusCode);
});
} else {
console.log(response.statusCode);
}
}
request(options, callback);
But the result is not all of the repositories, just the first page of all of them. How can I use pagination with the Request module? I've tried to find examples within the documentation, but they aren't that clear. Or do I need to do this with another library or maybe another language?
Thanks!
you should modify your querystring to include the value of "since". You can read more on the github documentation.
https://developer.github.com/v3/repos/#list-all-public-repositories
Sample URL with query string of since
https://api.github.com/repositories?since=364
You could use the pagination data provided in response.headers.link that's received when making calls to the GitHub API to find out if there are any more pages left for your call.
One approach is to loop through the pages until there are no more new pages left, at which point you can write to file and return from function.
On each loop you can add to the data that you already have by using concat (I assume that the response body is delivered as an array) and then passing on the data to the next function call.
I rewrote your code to include a basic implementation of such a technique:
var request = require('request');
var fs = require('fs');
var requestOptions = function(page) {
var url = 'https://api.github.com/repositories?page=' + page;
return {
url: url,
headers: {
'User-Agent': 'myusernamehere'
},
qs: {
stargazers: 5000
}
};
};
function doRequest(page, incomingRepos) {
request(requestOptions(page), function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.headers);
var currentPageRepos = JSON.parse(body);
var joinedRepos = incomingRepos.concat(currentPageRepos);
var linkData = response.headers.link;
// if response does not include reference to next page
// then we have reached the last page and can save content and return
if (!(linkData.includes('rel="next"'))) {
fs.writeFile('output_teste.json', JSON.stringify(joinedRepos), function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
return;
}
page++;
doRequest(page, joinedRepos);
} else {
console.log(response.statusCode);
}
});
}
doRequest(1, []);

Categories