Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sending HTTP response in node.js

Sending HTTP response in node.js

Problem

I am trying to send an Http Response in node to print results in the browser. The simplified source code is down below. Basically, all the variables are defined somewhere in the program, so that shouldn't be problem. When I try to run the script, I keep getting the error:

    http.js:783
        throw new TypeError('first argument must be a string or Buffer');

    TypeError: first argument must be a string or Buffer

So can someone familiar with node.js or javascript syntax let me know what the problem is?

    upload = function(req, res) {
        var fileInfos = [obj, obj];    //defined as an array of objects
        var counter = 0;           
        counter -= 1;
        if (!counter) {                
            res.end({files: fileInfos});    //files is defined. 
        }
        };

    async.forEach(urls, downloadFile, function (err) {    //all params defined. 
        if(err){
            console.error("err");
            throw err;
        }
        else{
            http.createServer(function(req, res){
            upload(req1, res);                       //req1 defined as an array of objects.
        }).listen(3000, "127.0.0.1");
        console.log('Server running at http://127.0.0.1:3000/');
    }
    });
Problem courtesy of: jensiepoo

Solution

This error is often caused by an attempt to call response.write with the wrong type of parameter. Looking at the documentation it suggests:

response.end([data], [encoding])#

This method signals to the server that all of the Response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

Now response.write( chunk, encoding ) expects the chunk to be a string, so it seems possible that when you are calling res.end({files: fileInfos}) it is unable to write the content of that object as a string.

Solution courtesy of: glenatron

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sending HTTP response in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×