简体   繁体   中英

Error: Can't set headers after they are sent. express js

Here I am trying to read a simple text file and put the content on my page. It's a very simply app but I am still having issues. Below is my code and I have also attached my github repo below.

https://github.com/shanemmay/ExpressJsProblem

const express = require('express');
const fs = require('fs');

const app = express();

app.get('/', (req,res) => 
{
    //trying to write some basic content to the page   
    fs.readFile('test.txt', (err, data) =>
    {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.send("<h1>test complete</h1>");
        res.write(data);

    });
});

app.post("/post", (req,res) =>
{
    //res.send("post");
});

app.listen(8080, () => console.log("App launched"));

Try replacing this block in your get function:

fs.readFile('test.txt', (err, data) =>
{
    res.set({
        'Content-Type': 'text/html'
    });
    res.status(200).send("<h1>test complete</h1>" + data);
});

That should duplicate the behavior you're looking for. The above will help you set headers if you need to, and explicitly set the status message, although, all you really need is this to do what you want:

res.send( "<h1>test complete</h1>" + data ); 
const fs = require('fs');
const filePath =  "/path/to/file" 
app.get('/', (req,res) => {
 fs.exists(filePath, function(exists){
      if (exists) {     
        res.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "attachment; filename=" + fileName
        });
        fs.createReadStream(filePath).pipe(res);
      } else {
        res.writeHead(400, {"Content-Type": "text/plain"});
        res.end("ERROR File does not exist");
      }
    });
});

To set the content type, we can use set method as below.

app.get('/', (req,res) => 
{
    //trying to write some basic content to the page   
    fs.readFile('test.txt', (err, data) =>
    {        
        res.set('Content-Type', 'text/html');
        res.send(data);       
    });
});

Ref: http://expressjs.com/en/4x/api.html#res.set

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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