gpt4 book ai didi

javascript - 在 ReactJS 中检索返回的 POST 数据

转载 作者:行者123 更新时间:2023-11-29 10:58:55 27 4
gpt4 key购买 nike

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

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

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,但出现以下错误:

Error Screenshot

我输出的 JSON 是:

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

我通过 Postman 进行了尝试,它运行良好。我不知道错误是什么!

最佳答案

response.json() 返回一个 promise ,因此在使用 setState 中的响应之前,请确保在 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 });
});

你也不应该用 this.getResponse 的结果调用 setState,因为你没有从 this.getResponse 返回任何东西,它是异步的。这将使您的 responseData 成为 undefined.

只需调用 this.getResponse 即可:

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

关于javascript - 在 ReactJS 中检索返回的 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com