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:
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!
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
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.