简体   繁体   中英

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

POST请求后返回的响应对象的图像

You need to call the json function and it will returns a promise, try that:

fetch(APP_SERVER_URL+'/login', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({name, password})
          }).then((response) => {
            response.json().then((data) => {
               console.log(data)
          });
          }).catch((error) => {
            console.log('Error', error); // no error is returned
            reject(error);
          })
        }

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

首先使用返回响应,然后再使用回调。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM