Reputation: 383
I'm having trouble with the res.send context. I do have the index.html
in my directory and it doesn't work as I'm expecting to. It just doesn't show my HTML file.
app.listen(8081, function(){
console.log("Servidor rodando na url http://localhost:8081");
});
app.get("/sendfile", function(req,res){
res.send("Página SENDFILE")
res.sendFile(__dirname + "index.html");
});
Here's what is showing in the localhost page:
Here's my directory:
Upvotes: 2
Views: 4378
Reputation: 17
app.get('/sendfile', async (req, res) => { ... })
block defines a route handler for the HTTP GET request to the /sendfile
endpoint. When a client sends a GET request to this endpoint, the code inside the block will execute.
Inside the route handler, res.sendFile()
is used to send the file located at the specified path to the client.
A single HTTP GET request can only have one response. In Express, the res.send()
or res.sendFile()
method is used to send a response back to the client. Once the response is sent, the request-response cycle is complete.
You cannot use both at a time.
Upvotes: 0
Reputation: 365
First of all it should produce error of
Headers can't be set once they are sent
.
Becuse once the response from :
res.send('Pagina SendFile')
is sent it won't send index.html
file.
You should first set the view Engine like this :
app.set('view engine', 'html');
in your server.js
file
And important of all you should keep all HTML
files in views then set view engine & finally send using :
res.status(200).sendFile(__dirname + 'index.html')
Upvotes: 2