teamyates
teamyates

Reputation: 434

Failing to log into loopback API using request

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.

Upvotes: 0

Views: 311

Answers (2)

isaacdre
isaacdre

Reputation: 892

  1. I like it when I see ; at the end of declarations :/. your var declarations need a lil ; :D
  2. 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.
  3. 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.
  4. 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":"[email protected]",
    "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;
});
  1. Good Luck!

Upvotes: 1

Your request should be like:

var userDetails = {
  "email": "[email protected]",
  "password": "test"
}

Upvotes: 0

Related Questions