我目前不熟悉React和Express,我希望发送从表单接收到的数据。我想发回的数据是处于状态的UserInfo或电子邮件。但是,我非常不确定应该如何处理此请求。
class ForgotPassword extends Component {
constructor() {
super()
this.state = {
email:'',
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
componentDidMount = () =>{
// this.fetchUserInfo();
}
handleChange = (e) => {
this.setState ({
[e.target.id]: e.target.value
})
console.log(this.state);
}
handleSubmit = async (e) => {
e.preventDefault();
const userInfo = {
email : this.state.email
};
fetch("/forgotpassword", {
method: "POST",
body: JSON.stringify(userInfo),
headers: { "Content-Type": "application/json" }
})
.then(response => {
return response.json();
})
.then(jsonData => {
console.log(jsonData);
})
.catch(err => {
console.log("Error with data fetch " + err);
});
};
This is my form...
<div className='row'>
<div className='col'></div>
<div className='col card form'>
<h1 id="title">Reset Password</h1>
<h5 id="passinstruc">Please enter your email to reset your password</h5>
<form id="forgotpass" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email </label>
<input onChange={this.handleChange} type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value={this.state.email} />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<button id="loginbtn" type="submit" className="btn btn-primary btn-lg btn-block" >Submit</button>
<br/>
<div className='division'>
<Link to="/register" className='btn btn-primary btn-lg btn-block' id="registerbtn" > Create your account here</Link>
</div>
</form>
</div>
在后端,我收到POST / forgotpassword 404消息,但是我不知道为什么。帮助将不胜感激。
这是我将在其中发送信息的后端路由
var express = require('express');
var router = express.Router();
var connection = require ('../connection');
var email = require ('./sendEmail');
router.post('/forgotpassword', function(req, res, next) {
console.log(req.email);
var userEmail = req.email;
var text = "Follow the instructions below to reset your password"
email.sendEmailWithTemplate(userEmail,'PetS.o.S Password Reset', text);
});
答案 0 :(得分:0)
要发送数据,您将需要服务器的域名或IP地址。
一旦获得了这些,就可以使用jQuery.get-https://api.jquery.com/jQuery.get/
或jQuery.post- https://api.jquery.com/jQuery.post/
或者,如果您不使用jQuery,请使用XMLHttpRequest- https://www.w3schools.com/xml/xml_http.asp
答案 1 :(得分:0)
而不是在正文中发送数据而是作为响应发送它。
fetch('/ api / getList') .then(res => res.json()) .then(list => this.setState({list}))
https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3