【问题标题】:How can I use state to make a POST fetch request on my backend如何使用状态在我的后端发出 POST 获取请求
【发布时间】:2020-02-27 22:52:39
【问题描述】:

我现在正在开发我的第一个应用程序,它是在 react native 中为前端创建的,并使用 Node JS 作为后端,使用 mongodb 作为数据库。 我正在尝试为我的用户实现注册表单,但我真的不知道如何对状态执行此操作,因为它一直说无法评估 this.state.name。 我想做的是使用 fetch api 注册一个使用 Postman 工作的帐户的 POST 请求,因此错误来自我的前端。

所以我要做的是创建我的函数来执行此操作,但我希望正文代表用户在不同字段中键入的值,我存储在状态中,当您看到代码时它会很清楚。 如果我使用状态它不起作用但是如果我直接在我的函数中输入一些值它会起作用。

这第一件事是我的 fetch API 函数,如果我这样做它不起作用,下面是我如何获取每个字段的状态(请参阅)

clickthebutton = () =>{
    //var data = this.state
    fetch('http://localhost:5050/api/new/register',{
        method:'POST',
        headers : {'Content-Type': 'application/json'},
        body : {
            name:this.state.name,
            age:this.state.age,
            password:this.state.password,
            email:this.state.email
        },       
    })
}
<Input
                        label="Your email address"
                        placeholder="yo@gmail.com"
                        onChangeText={(text)=> this.setState({email:text})}
                        value={this.state.email}
>

我的状态是这样的:

this.state={
            email:null,
            password:null,
            name:null,
            age:null,
            dataImage:null
        }

我想发送正文,如果我做 body : this.state 当我在我的服务器上执行 console.log(req.body) 时它不会发送任何内容,它会显示一个空对象。

感谢您的帮助

编辑:问题已解决,我的函数不是指我的班级。

【问题讨论】:

标签: node.js api react-native fetch


【解决方案1】:

首先,您需要为您的电子邮件和密码输入正确的元素,例如(对于电子邮件):

<TextInput
    value={this.state.name}
    keyboardType={'email-address'}
    placeholder="Your email address"
    onChangeText={text => this._onEmailChange(text)}
/>

您还需要一个函数来更新名称值(您将需要一个类似的函数来更新来自 TextInput 元素的任何值)

_onEmailChange = text => {
    this.setState({ name: text });
};

然后您可以按照以下方式准备您的请求

fetch('http://localhost:5050/api/new/register', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email: this.state.name,
      password: this.state.password
      ...
    }),
})
.then(response => response.json())
.then(responseJson => {
  // do what you want with the response here
})
.catch(error => {
    console.error(error);
});

【讨论】:

  • 你好,我使用 react native 元素作为输入,这就是为什么我使用 Input 而不是 TextInput 但它们的作用相同,我还有 onChange() 函数用于更新每个字段的状态。
【解决方案2】:

您已在发送时以json 格式发送的标头中指定。发送到服务器时,必须转换为jsonString

fetch('http://localhost:5050/api/new/register', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name:this.state.name,
    age:this.state.age,
    password:this.state.password,
    email:this.state.email
  }),
});

好的你可以试试Formdata

let formdata = new FormData();
      formdata.append("name", this.state.name);
      formdata.append("age", this.state.age);
      formdata.append("password", this.state.password);
      formdata.append("email", this.state.email);
fetch('http://localhost:5050/api/new/register', {
    method: 'POST',
    headers: {
      "Content-Type": "multipart/form-data"
    },
    body: formdata
})
.then(res => res.json())
.then(reponse => {
  console.log(reponse)
})
.catch(error => {
    console.error(error);
});

【讨论】:

  • 嘿,是的,这就是我最初所做的,但它不起作用。
  • @Louisnot 我是你的修改,我在 cmets 中的答案。
【解决方案3】:

在获得您所在州的所有表单数据后,您有两个选项可以向后端发出请求。

Content-Type 设置为application/text 或删除header

fetch('http://localhost:5050/api/new/register',{
        method:'POST',
        headers : {'Content-Type': 'application/text'},
        body : {
            name:this.state.name,
            age:this.state.age,
            password:this.state.password,
            email:this.state.email
        },       
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2019-03-13
    • 2021-02-11
    • 1970-01-01
    • 2015-05-28
    • 2014-06-20
    相关资源
    最近更新 更多