admin管理员组

文章数量:1303411

I've been trying to call a server-side POST function to authenticate a user in a web-application. Both my ExpressJS and my ReactJS environments are configured and running correctly, one on port 3000 and one on 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. 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:

Error Screenshot

My outputted JSON is:

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

I tried it through Postman and it's working fine. I can't figure out what the error is!

I've been trying to call a server-side POST function to authenticate a user in a web-application. Both my ExpressJS and my ReactJS environments are configured and running correctly, one on port 3000 and one on 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. 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:

Error Screenshot

My outputted JSON is:

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

I tried it through Postman and it's working fine. I can't figure out what the error is!

Share edited Jul 8, 2018 at 10:47 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Jul 8, 2018 at 10:17 Raju ThondeRaju Thonde 531 gold badge1 silver badge4 bronze badges 5
  • does responseData have a value in your state initially? If it's initially undefined, then you'll get that error. The fetch is asynchronous so the ponent will render first, before the fetch response es back – Jayce444 Commented Jul 8, 2018 at 10:21
  • 1 @Jayce444 yes it does! I've filled it with dummy JSON data. – Raju Thonde Commented Jul 8, 2018 at 10:33
  • @RajuThonde Could you include the rest of your ponent in your question? – Tholle Commented Jul 8, 2018 at 10:37
  • 1 @Tholle Done, updated the source code. – Raju Thonde Commented Jul 8, 2018 at 10:44
  • @RajuThonde You should just call this.getResponse in your handleSubmit method, not call setState with it. Since you are not returning anything from this.getResponse, that will make responseData be undefined. – Tholle Commented Jul 8, 2018 at 10:49
Add a ment  | 

2 Answers 2

Reset to default 4

response.json() returns a promise, so make sure you return that in the promise chain before you use the response in 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 });
  });

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. That will make your responseData be undefined.

Just call this.getResponse instead:

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:

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

So in React code you retrieve it like that:

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

本文标签: javascriptRetrieving returned POST data in ReactJSStack Overflow