简体   繁体   中英

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

I have a little problem who's block me. I create a little API with nodeJS and I would like to send a files contents.

I recuperate data with angular.

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

router.get('/posts', (req, res) => {
    fs.readdir('./maps', function(error, files) {
        if(error)
            throw error;

        files.forEach(file => {
            fs.readFile(file, (err, data) => {
                res.send(data);
            });
        });
    })
});

Thanks for help.

Well you cannot send multiple responses to the request. You have to read all the files synchronously and make ONE res.send with all the files you got.

You can not call res.send() in a for loop. It has to be executed only once as it is sending response back to the caller of the api. What you can do is concatenate the response in the for loop and send it at the end.

router.get('/posts', (req, res) => {
        fs.readdir('./maps', function(error, files) {
            if(error)
                throw error;
            var responseData = '';
            files.forEach(file => {
                fs.readFile(file, (err, data) => {
                    responseData += data; 
                });
            });
            res.send(responseData);
        })
    });

The problem is that in the above code you are trying to send a response every time you read a file

files.forEach(file => {
            fs.readFile(file, (err, data) => {
                res.send(data);//repeated sending of response 
            });
        });

If you are planning to send a response after reading all file what you need to is to read in parallel and once all read are done then you can send the response. For doing that you can use the async or promise library which help you do this with ease

async.each(files, function(file, callback) {
    fs.readFile(file, (err, data) => {
                callback(); 
            });

}, function(err) {
    res.send(data);
});

As a result, only once all the file are read the response is send.

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