如何使用fetch in native native发布表单?

时间:2015-06-05 09:17:11

标签: javascript reactjs react-native

我尝试使用react-native fetch api发布包含first_name,last_name,email,password和password_confirmation的表单。

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的回应。怎么做?

2 个答案:

答案 0 :(得分:7)

所以,如果我理解你,你希望它发布相同的字符串,但只是没有花括号?

如果是这种情况,你可以从字符串中删除它们。

  

.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, "")
})

答案 1 :(得分: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
})