Tiburoncin23
Tiburoncin23

Reputation: 17

Why is `res.sendFile` not doing anything? No errors, but nothing happens

For some reason res.sendFile in a post method isnt working at all. Like there is no error, but it isnt working. Let me show you the code

app.post('/login',(req, res) => {
  var password = req.body.password;
  //console.log(password) <- it logs it correctly
  
  if(password == 'hey'){
    res.sendFile(path.resolve(__dirname, 'public/index2.html');
    res.end('yes')
  }else{
    res.end('no');
  }
 
});

I also tried changing the path.resolve for path.join and it's doing literally nothing. I added a console.log('hey') and it actually logs that. But it doesnt load the file html.

    <script>
      $(document).ready(function(){
        var pass;
        $('#submit').click(function(){
          pass=$('#password').val();
          $.post("https://heresmypage.repl.co/login",{password: pass}, function(data){
            if(data === 'no'){
              alert("Password is not correct.");
            }
          });
        })
      })
    </script>
<input placeholder="Password" id="password">
<input type="submit" value="Submit" id="submit"></button>

Answers will be much appreciated

Upvotes: 0

Views: 2628

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075427

I can see a few possible reasons:

  1. You're ending the response before it has a chance to send the file by calling end().

    When you use sendFile(), you don't call end; it does it for you. (This is true of most of the Response methods that send information — send, json, etc.)

    From the end documentation:

    Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.

    Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

    (my emphasis on "instead")

  2. There's a syntax error in the quoted code: You're missing a ) on the sendFile call. That makes me think this isn't the code you're actually running (since you'd get an error), so perhaps the sendFile call isn't in the code you're actually running.

  3. It may be sending the file, but the browser may be blocking access to it because of the Same Origin Policy if the page you're running that code on isn't from https://heresmypage.repl.co.

If I fix #1 and #2 and ensure that #3 doesn't apply, it works just fine; see *** comments:

index.js:

const express = require("express");
const path = require("path");

const app = express();

app.use(express.urlencoded());

app.post('/login',(req, res) => {
    var password = req.body.password;
    //console.log(password) <- it logs it correctly
    
    if(password == 'hey'){
      res.sendFile(path.resolve(__dirname, 'public/index2.html'));
      // *** Added ) −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^
      // *** Removed call to `res.end('yes');` here
    }else{
      res.end('no');
    }
});

app.get("/", (req, res) => {
    res.sendFile(path.resolve(__dirname, "public/index.html"));
});
  
app.listen(3000);

public/index.html:

<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>sendFile Question</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <style>
        html {
            box-sizing: border-box;
        }

        *,
        *:before,
        *:after {
            box-sizing: inherit;
        }
    </style>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            var pass;
            $('#submit').click(function () {
                pass = $('#password').val();
                $.post("/login", { password: pass }, function (data) {
                //     ^^^^^^^^−−−−−− removed the hardcoded path so the request is relative, to ensure
                // the SOP isn't the issue
                    console.log(data);
                    if (data === 'no') {
                        alert("Password is not correct.");
                    }
                });
            })
        })
    </script>
    <input placeholder="Password" id="password">
    <input type="submit" value="Submit" id="submit"></button>
</body>

</html>

public/index2.html:

<p>Hi</p>

Using the password hey gets me the contents of index2.html in data.

Upvotes: 2

Related Questions