我正在尝试使用 React 和 Node/Express/(mongo) 作为后端构建一个登录/注册表单。 后端工作正常。当我向/register 发送 POST 请求(使用 postman )时,一切正常并且凭据存储在数据库中。
我现在尝试在客户端上使用 React 来实现表单,但是当我尝试 POST 时,我总是收到错误:未处理的拒绝(类型错误):无法获取
。
这是我的代码:
import React, { Component } from 'react';
class Register extends Component {
state = { email: '', password: '' };
handleInputChange = event => {
const { value, name } = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
fetch('localhost:3000/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
});
};
render() {
return (
<form onSubmit={this.onSubmit} noValidate>
<h1>Login</h1>
<input
type="email"
name="email"
placeholder="Enter email"
value={this.state.email}
onChange={this.handleInputChange}
/>
<input
type="password"
name="password"
placeholder="Enter password"
value={this.state.password}
onChange={this.handleInputChange}
/>
<input type="submit" value="Submit" />
</form>
);
}
}
export default Register;
如果有帮助,我们将不胜感激:)
最佳答案
您需要使用 then block 来实际调用您的 api。
onSubmit = event => {
event.preventDefault();
fetch("localhost:3000/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then(res => {
console.log("response: ", res);
})
.catch(err => {
console.log("error:", err);
});
};
关于javascript - 未处理的拒绝(类型错误): Failed to fetch (POST) react/node/express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61011609/