简体   繁体   English

在ReactJS中检索返回的POST数据

[英]Retrieving returned POST data in ReactJS

I've been trying to call a server-side POST function to authenticate a user in a web-application. 我一直在尝试调用服务器端POST函数来验证Web应用程序中的用户。 Both my ExpressJS and my ReactJS environments are configured and running correctly, one on port 3000 and one on 3001. 我的ExpressJS和我的ReactJS环境都配置正确,一个在端口3000上,另一个在3001上。

I'm able to call the functions and execute the server-side Express code, however when I try to access the returned value in React, the value appears to be undefined. 我能够调用函数并执行服务器端的Express代码,但是当我尝试访问React中的返回值时,该值似乎未定义。 Would love some help! 会爱一些帮助!

React Code: 反应代码:

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>
    );
  }
}

I'm later trying to access reponseData.key, and I get the following error: 我后来试图访问reponseData.key,我收到以下错误:

Error Screenshot 错误截图

My outputted JSON is: 我输出的JSON是:

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

I tried it through Postman and it's working fine. 我通过Postman尝试了它,它工作正常。 I can't figure out what the error is! 我无法弄清楚错误是什么!

response.json() returns a promise, so make sure you return that in the promise chain before you use the response in setState . response.json()返回一个promise,因此在使用setState的响应之前,请确保在promise链中返回该promise。

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 });
  });

You should not call setState with the result from this.getResponse either, since you are not returning anything from this.getResponse and it is asynchronous. 你不应该调用setState从结果this.getResponse或者,因为你没有从回国任何this.getResponse ,它是异步的。 That will make your responseData be undefined. 这将使您的responseData undefined.

Just call this.getResponse instead: 只需调用this.getResponse

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

For example you're returning data from .post like that: 例如,您将从.post返回数据:

app.post('/', function (req, res) {
// server side code
    res.json(/*returning data*/);
});

So in React code you retrieve it like that: 所以在React代码中你可以像这样检索它:

functionThatMakePostRequest = (args) => {
const data = {
    id: 555,
    name: "name",
};

fetch('/', {
    method: 'post',
    body: JSON.stringify(data),
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
})
.then(res => res.json()) //returns array of data
.then(res => this.setState({ res })); //assign state to array res
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM