Search code examples
javascripthtmlexpresshttp-status-codes

Can you send a status code and a html web page?


I am using the express framework in node and I don't know what is best practice or if this is the wrong thing to do but I wanted to send a status code e.g. res.status(200).send("Success"); if the form input matches with the server and if it does not match then send something like res.status(403).send("Forbidden"); Then in the webpage I can update the paragraph element with the sent response. So the user knows if it has been successful or not.

Is this possible? If it is how do I do it? And is there a better way?


Solution

  • For sure it is possible!
    Taken from the express api reference:

    res.status(code)
    Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

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

    Generally sending status codes is the way to go. If you are sending data without a status code, express will add the 200 status code automatically, so you don't have to add it manually.

    On the client side, you have to check for a non 2xx status code in your response object of your request. Here is an example using the 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);
          });
    
    


    Example: Credentials Use Case
    If you want to write a web page which has a form to enter user credentials to gain access to further content, I would suggest doing it the following way:

    • Client side:
        // 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);
            });
    
        }
    
    • Server side:
        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.');
          });
        });