我在node中使用express框架,我不知道什么是最佳实践,或者这是做错了什么,但是我想发送一个状态代码,例如res.status(200).send("Success");
如果表单输入与服务器匹配,并且不匹配,则发送类似res.status(403).send("Forbidden");
的信息然后,在网页中,我可以使用发送的响应更新段落元素。因此用户知道它是否成功。
这可能吗?如果是我该怎么办?还有更好的方法吗?
肯定有可能!取自Express API参考:
res.status(code)设置响应的HTTP状态。它是Node的response.statusCode的可链接别名。
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
通常,发送状态代码是一种方法。如果您发送的数据没有状态码,则express将自动添加200个状态码,因此您不必手动添加。
在客户端,您必须在请求的响应对象中检查非2xx状态代码。这是使用提取API的示例。
fetch('/your/api')
.then((response) => {
if (!response.ok) { // Check for a non 2xx status code
throw new Error('Network response was not ok');
}
// Do something with the response data
})
.catch((error) => {
// This is only reached when a network error is encountered or CORS is misconfigured on the server-side
console.error('There has been a problem with your fetch operation:', error);
});