首页 > 解决方案 > 我们如何从 react native 的 fetch 函数中获取 post 数据来表达 api?

问题描述

问题:

我们如何从 react native 中的 fetch 函数中获取 post 数据以表达 api?

面临的问题:

我尝试了以下过程,但没有在后端 API 中获得这些变量。

如何在后端 API 中实现变量?任何建议都受到高度赞赏。

这是反应式本机获取功能:

反应本机获取功能:

 login = async () => {

   await fetch('http://192.168.1.160:8001/api/login', {
          method: 'POST',
          mode: 'cors',
          cache: 'default',
          header: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },

          body: JSON.stringify({
              email: this.state.email,
              password: this.state.password
          })
    })
    .then ((response) =>  response.json())
    .then ((res) => {//console.log(res);
        if(res.error === false){
            AsyncStorage.setItem('user', res.data);
            this.props.navigation.navigate('profile');
        } else{
           // alert(res.message);
        }
    })

  }

Express-API:

快递API如下:

    module.exports = function (req, res) {
console.log('TEST',req.body);
  let { email, password } = req.body;

  let input = { email, password };

  const validator = loginValidator(input);

  if (validator.error) {

    return res.status(400).json({
      error: true,
      message: validator.error.details,
    });

  } else {

    models.users.findOne({
      where: { email: email }
    }).then(user => {

      if (!user) {
        return res.status(400).json({
          error: true,
          message: {
            key: 'email',
            text: MessageHelper.email_already_exist
          }
        });

      } else if (!bcrypt.compareSync(password, user.password)) {

        return res.status(400).json({
          error: true,
          message: {
            key: 'password',
            text: MessageHelper.password_not_valid
          }
        });

      } else {

         var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
          models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){ 
                return res.json({
                    error: false,
                    message: MessageHelper.user_token_updated,
                   token: token,  
                   data: {
                        user_id: user.id,
                        firstname: user.firstname,
                        lastname: user.lastname,
                        username:user.username,
                        email: user.email,
                        mobile: user.mobile,
                        token: user.token
                        }
                });
            }).catch(function(error){
                return res.status(400).json({
                    error: true,
                    message: error
                });
            })

      }

    });

  }

}

标签: expressreact-native

解决方案


Fetch 还接受一个可选的第二个参数,允许您自定义 HTTP 请求。您可能想要指定其他标头,或发出 POST 请求:

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

联网本质上是一种异步操作。Fetch 方法将返回一个 Promise,这使得编写以异步方式工作的代码变得简单:

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
}

推荐阅读