javascript 如何在 React Native 中使用 fetch 发布表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30662782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post a form using fetch in react native?
提问by Piyush Chauhan
I'm trying to post the form containing the first_name, last_name, email, password and password_confirmation using react-native fetch api.
我正在尝试使用 react-native fetch api 发布包含 first_name、last_name、电子邮件、密码和 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,
})
})
Output in Rails console
Rails 控制台中的输出
Parameters: {"{\"config_name\":\"default\",\"first_name\":\"Piyush\",\"last_name\":\"Chauhan\",\"email\":\"[email protected]\",\"password\":\"diehard4\",\"password_confirmation\":\"diehard4\"}"=>"[FILTERED]"}
Unpermitted parameter: {"config_name":"default","first_name":"Piyush","last_name":"Chauhan","email":"[email protected]","password":"diehard4","password_confirmation":"diehard4"}
So, its posting the whole value as string and rails is parsing the string as a variable. I want to strip out the "{" from the json response. How to do it ?
因此,它将整个值作为字符串发布,而 rails 将字符串解析为变量。我想从 json 响应中去掉“{”。怎么做 ?
采纳答案by rmuller
so if I understand you well, you want it to post the same string but just without the curly braces?
因此,如果我理解您的意思,您是否希望它发布相同的字符串但不带花括号?
If that's the case, you can just strip them from the string.
如果是这种情况,您可以将它们从字符串中剥离。
.replace(/{|}/gi, "")
.replace(/{|}/gi, "")
so that would look as follows
所以看起来如下
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, "")
})
回答by Julio Araya Cerda
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
})