首页 > 解决方案 > 在 ReactJS 中检索返回的 POST 数据

问题描述

我一直在尝试调用服务器端 POST 函数来验证 Web 应用程序中的用户。我的 ExpressJS 和我的 ReactJS 环境都已正确配置和运行,一个在端口 3000 上,一个在 3001 上。

我能够调用函数并执行服务器端 Express 代码,但是当我尝试访问 React 中的返回值时,该值似乎未定义。希望得到一些帮助!

反应代码:

import React, { Component } from 'react';

export default class tem extends Component {
  constructor(props) {
    super(props);

    var testVar = {
      key: "0000000000",
      status: false
    };
    this.state = {
      users: [],
      username: "",
      password: "",
      submitted: "yes",
      responseData: testVar
    };
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handlePassChange = this.handlePassChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getResponse = this.getResponse.bind(this);
  }

  handleNameChange(e) {
    this.setState({ username: e.target.value });
  }
  handlePassChange(e) {
    this.setState({ password: e.target.value });
  }

  getResponse(urlPath, user, pass) {
    let setResp = this;
    fetch(urlPath, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password
      })
    })
      .then(function(response) {
        return response.json();
      })
      .then(function(response) {
        setResp.setState({ responseData: response });
      });
  }

  handleSubmit(event) {
    event.preventDefault();
    this.setState({ submitted: "YES" });
    this.setState({
      responseData: this.getResponse(
        "/login",
        this.state.username,
        this.state.password
      )
    });
  }

  render() {
    return (
      <div>
        <h1>login </h1>
        Enter your username
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            placeholder="Search..."
            value={this.props.filterText}
            onChange={this.handleNameChange}
          />
          Enter your password
          <input
            type="password"
            placeholder="enter password"
            value={this.props.filterText}
            onChange={this.handlePassChange}
          />
          <button type="submit">Start</button>
        </form>
        {this.state.responseData.key}
        {this.state.submitted}
      </div>
    );
  }
}

我稍后尝试访问reponseData.key,我收到以下错误:

错误截图

我输出的 JSON 是:

{
    "key": "408f51qk54",
    "status": true
}

我通过邮递员尝试过,它工作正常。我无法弄清楚错误是什么!

标签: javascriptreactjs

解决方案


response.json()返回一个承诺,因此请确保在使用setState.

let setResp = this;
fetch(urlPath, {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    username: this.state.username,
    password: this.state.password
  })
})
  .then(function(response) {
    return response.json();
  })
  .then(function(response) {
    setResp.setState({ responseData: response });
  });

您不应该使用其中任何一个setState的结果进行调用this.getResponse,因为您没有返回任何内容this.getResponse并且它是异步的。这会让你responseData成为undefined.

只需调用this.getResponse

handleSubmit(event) {
  event.preventDefault();
  this.setState({ submitted: "YES" });
  this.getResponse(
    "/login",
    this.state.username,
    this.state.password
  );
}

推荐阅读