【问题标题】:How to post a form using fetch in react native?如何在本机反应中使用 fetch 发布表单?
【发布时间】:2015-08-20 04:23:16
【问题描述】:

我正在尝试使用 react-native fetch api 发布包含名字、姓氏、电子邮件、密码和密码确认的表单。

fetch('http://localhost:3000/auth', {
  method: 'post',
  body: JSON.stringify({
    config_name: 'default',
    first_name: this.state.first_name,
    last_name: this.state.last_name,
    email: this.state.email,
    password: this.state.password,
    password_confirmation: this.state.password_confirmation,
  })
})

Rails 控制台中的输出

Parameters: {"{\"config_name\":\"default\",\"first_name\":\"Piyush\",\"last_name\":\"Chauhan\",\"email\":\"piyushchauhan2011@gmail.com\",\"password\":\"diehard4\",\"password_confirmation\":\"diehard4\"}"=>"[FILTERED]"}
Unpermitted parameter: {"config_name":"default","first_name":"Piyush","last_name":"Chauhan","email":"piyushchauhan2011@gmail.com","password":"diehard4","password_confirmation":"diehard4"}

因此,将整个值发布为字符串,rails 将字符串解析为变量。我想从 json 响应中去掉“{”。怎么办?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    所以如果我理解你的话,你希望它发布相同的字符串但不带花括号?

    如果是这样,您可以将它们从字符串中剥离。

    .replace(/{|}/gi, "")

    所以看起来如下

    fetch('http://localhost:3000/auth', {
    method: 'post',
    body: JSON.stringify({
      config_name: 'default',
      first_name: this.state.first_name,
      last_name: this.state.last_name,
      email: this.state.email,
      password: this.state.password,
      password_confirmation: this.state.password_confirmation,
      }).replace(/{|}/gi, "")
    })
    

    【讨论】:

      【解决方案2】:
      const m = encodeURIComponent(userEmail);
      const p = encodeURIComponent(userPassword);
      const requestBody = `email=${m}&pass=${p}`;
      fetch(`http://server.com`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: requestBody
      })
      

      【讨论】:

      • 请提供详细信息并解释更多
      猜你喜欢
      • 2019-02-05
      • 2018-03-20
      • 2021-09-24
      • 2019-05-19
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2017-09-23
      • 2023-03-17
      相关资源
      最近更新 更多