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. Thefetch
is asynchronous so the ponent will render first, before thefetch
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 yourhandleSubmit
method, not callsetState
with it. Since you are not returning anything fromthis.getResponse
, that will makeresponseData
beundefined
. – Tholle Commented Jul 8, 2018 at 10:49
2 Answers
Reset to default 4response.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
版权声明:本文标题:javascript - Retrieving returned POST data in ReactJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741667601a2391406.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论