Wednesday, 3 May 2017

Returning JSON within the same Fetch POST API call

I currently have a web app built on the Express framework for Node.js.

I'm now building a React Native app that needs to perform user login. To do this, I've created a mongo-helpers.js file that will simply perform the api calls to localhost:3000/api and return JSON. So far, I've had no problem making GET calls and receiving data, however here is my problem and what I want to do:

Objective: When the Login button is pressed (in the React Native app) make an API call to localhost:3000/api/login, passing the username and password into the body of the fetch API POST request. If the user is logged in, send back the user's Mongo Document.

Problem: Though I am able to make the API Post request and successfully log in the user, I am unable to send back the user's Mongo document with res.json(user)

Here is my code:

Express WEB APP: routes/api/api.js

// POST and login user
router.post('/login', (req, res) => {
  user.findOne({name: req.body.name, password: req.body.password})
    .then((user) => {
      console.log(user);
      res.json(user)
    })
    .catch((error) => res.json(error))
});

React Native App: mongo-helpers.js

// Returns a promise
//  if login succeeds then return the user
//  if login fails return error
exports.login = (name, password) => {
  return new Promise(
    (resolve, reject) => {
      fetch(APP_SERVER_URL+'/login', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({name, password})
      }).then((response) => {
        console.log('Response', response);
      }).then((data) => {
        console.log(data); // returns undefined :(
        resolve(data);
      }).catch((error) => {
        console.log('Error', error); // no error is returned
        reject(error);
      })
    }
  )
};

I am logging the response and here is what it shows. There's no user data within it

image of response object returned after POST request



via szier

No comments:

Post a Comment