首先你需要声明状态:
const [value, setValue] = usestate('');
const [error, setError] = useState('');
要执行验证,您可以在服务器中创建一个函数:
const validateInput = (val) => {
//...do your check here and return the data if valid (with 200 response code) or an error with a message what is wrong with 400 code
}
此外,您可以在前端进行验证:
const handleSubmit = () => {
//... do checks on `value` state parameter, if all is OK, send request to server, else setError() with reason and show it in some form of alert to user
}
然后是一个基本形式:
<form onSubmit={handleSubmit}>
// Some Alert Component
<Alert hidden={!error} value={errror} />
<input value={value} onChange={e => setValue(e.target.value)}/>
<button type='submit'></button>
</form>
在服务器上,您可以编写一个首先检查然后添加到 DB 的函数(下面的代码在带有 TS 的节点中):
export const addSongToDB = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
// Server-side validaiton
if (!req.body.URL || !req.body.name)
return next({ status: 400, message: 'Song URL and name are mandatory' });
const newSong = await db.Song.create(req.body);
const {
id,
name,
URL,
posterURL,
artist,
album,
composer,
genre,
year,
playedOn,
} = newSong;
return res.status(200).json({
id,
name,
URL,
posterURL,
artist,
album,
composer,
genre,
year,
playedOn,
});
} catch (error) {
console.log(error);
// This next() goes to the error handler of the server
return next({
status: 500,
message: error.message,
});
}
};
我在后端创建了一个通用错误处理程序,以改善前端开发人员的生活:
const errorHandler = (
error: CustomError,
req: Request,
res: Response,
next: NextFunction
) =>
res.status(error.status || 500).json({
error: {
message: error.message || 'Oops.. something went wrong!',
},
});
export default errorHandler;