亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

你能發送一個狀態碼和一個html網頁嗎?

你能發送一個狀態碼和一個html網頁嗎?

皈依舞 2022-06-16 15:38:22
我在節點中使用 express 框架,我不知道什么是最佳實踐,或者這是否是錯誤的做法,但我想發送一個狀態碼,例如res.status(200).send("Success");表單輸入是否與服務器匹配,如果它不匹配然后發送類似res.status(403).send("Forbidden"); Then 在網頁中的內容,我可以使用發送的響應更新段落元素。所以用戶知道它是否成功。這可能嗎?如果是我該怎么做?還有更好的方法嗎?
查看完整描述

1 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

肯定有可能!

取自 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 狀態代碼。這是一個使用 fetch 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);

      });


示例:憑據用例

如果您想編寫一個網頁,該網頁具有輸入用戶憑據以訪問更多內容的表單,我建議您按照以下方式進行操作:

客戶端:

    // 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.');

      });

    });


查看完整回答
反對 回復 2022-06-16
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號