我是新手反应和表达,我正在使用vanilla反应,即使用它作为html文件加载来自CDN的反应:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
我已经使用reactjs:
创建了注册和登录表单
<script type="text/babel">
class SignUpForm extends React.Component { render() { return(
<div id="signup">
<form method="post" action="/signup/">
<div class="form-group">
<label>Email:</label>
<input type="email" className="form-control" required placeholder="Email" id="Email" name="userid" onChange={this.handleChange} autofocus />
<p id="ERR_EMAIL"></p>
<label>Password:</label>
<input type="password" className="form-control" required placeholder="password" id="Password" name="password" minLength="8" maxlength="16" onChange={this.handleChange} />
<p id="ERR_PASSWORD"></p>
<label>Confirm Password:</label>
<input type="password" className="form-control" required placeholder="password" id="Conpassword" minLength="8" maxlength="16" onBlur={this.handleComp} />
</div>
<button type="submit" className="btn btn-default btn-md theme" id="loginbtn" onClick={this.handleClick}>Sign Up</button>
</form>
<div class="alert-warning" id="ERR_MSG">{this.state.error}</div>
<a href="#" onClick={this.handleLinkClick}>Already a member login</a>
</div>); } }
</script>
我正在快递中执行服务器端验证:
app.post('/signup/', function(req, res) {
req.body.username;
req.body.password
/* some valdiation code*/
/*....*/
//how do I send output back to html page where I am using react to render component
}
我的问题是如果客户端提交的数据出错,如何将错误消息传回客户端
答案 0 :(得分:2)
例如: 服务器端:
router.post('/user', (req, res, next) => {
login = req.body.login;
password = req.body.password;
....//your validation logic
if (isDataInvalid) {
res.json({ statusCode: 400, message: "data is invalid" });
} else {
res.json({ statusCode: 200 });
}
});
客户端:
login (login, password) {
return new Promise ((resolve, reject) => {
fetch (`http://yourserver.com/user`, {
method: "post",
headers: {
"Content-Type" : "application/json"
},
body: JSON.stringify({login: login, password: password})
}).then(response => response.json())
.then(response => resolve(response))
.catch(error => { console.log(error); reject(error);});
})
}
并且
this.login(login, password).then(response => {
if (response.statusCode === 400) alert (response.message);
});
答案 1 :(得分:1)
取决于您如何构建应用程序。
如果您的后端是JSON API,那么您可以将其作为JSON发回,即
return res.status(422).json({errors: {
email: 'Invalid email address provided',
password: 'Invalid password'
}});
如果您的应用在服务器端呈现,那么请将错误包含在您发回的HTML模板中。