繁体   English   中英

你能发送一个状态码和一个 html web 页面吗?

[英]Can you send a status code and a html web page?

我在节点中使用 express 框架,我不知道最佳实践是什么,或者这是否是错误的做法,但我想发送一个状态码,例如res.status(200).send("Success"); 如果表单输入与服务器匹配,如果不匹配,则发送类似res.status(403).send("Forbidden"); 然后在网页中,我可以使用发送的响应更新段落元素。 所以用户知道它是否成功。

这可能吗? 如果是我该怎么做? 还有更好的方法吗?

肯定有可能!
取自快递 api 参考资料:

res.status(代码)
设置响应的 HTTP 状态。 它是 Node 的 response.statusCode 的可链接别名。

    res.status(403).end()
    res.status(400).send('Bad Request')
    res.status(404).sendFile('/absolute/path/to/404.png')

一般发送状态码是go的方式。 如果您发送的数据没有状态码,express 会自动添加 200 状态码,您无需手动添加。

在客户端,您必须在请求的响应 object 中检查非 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);
      });


示例:凭证用例
如果您想编写一个 web 页面,该页面具有输入用户凭据以访问更多内容的表单,我建议您通过以下方式进行操作:

  • 客户端:
 // Function is listening to the submit event of your login form function submitLoginForm() { let username = document.getElementById("username").value; let password = document.getElementById("password").value; const options = { method: 'POST', body: JSON.stringify({ username, password }), headers: { 'Content-Type': 'application/json' } }; return fetch('/api/login', options).then((response) => { // Check for a non 2xx status code if (.response.ok) { // Show a failed login hint showMessageBox('Login was not granted by the server. Please check you user name or password and try again,'; 'error'), } // Your login was successfull, manually redirect to user's dashboard. or whatever content... }).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); }); }
  • 服务器端:
 app.post('/api/login', (req, res, next) => { let username = req.body.username; let password = req.body.password; checkCredentials(username, password, (err) => { if (err) { return res.status(400).send('Wrong user name or password.'); } // Consider adding a token or a cookie to the response object, so that the user keeps logged in. return res.send('Access granted.'); }); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM