0

I'm using sailsjs and I'm trying to return the response with JSON content type. Don't know why

        Application.getEmailDuplicateCheck(options, function(error, result) {

            console.log('Email duplicate check error', error);
            console.log('Email duplicate check result', result);

            if (error) {
                return res.serverError(error);
            }

            if (result) {
                return res.ok(result); /*** THIS IS LINE 180 ***/
            }
        });

And not sure why the it always says that "Can't set the headers after they are sent" because I put all the response with return;

> Error: Can't set headers after they are sent.
>         at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
>         at ServerResponse.res.setHeader (/home/apps/cat/api/node_modules/express/node_modules/connect/lib/patch.js:134:22)
>         at ServerResponse.res.set.res.header (/home/apps/cat/api/node_modules/express/lib/response.js:595:10)
>         at ServerResponse.res.send (/home/apps/cat/api/node_modules/express/lib/response.js:151:12)
>         at ServerResponse.res.json (/home/apps/cat/api/node_modules/express/lib/response.js:237:15)
>         at ServerResponse.res.send (/home/apps/cat/api/node_modules/express/lib/response.js:139:21)
>         at /home/apps/cat/api/api/controllers/DuplicateCheckController.js:180:16
Yansen Tan
  • 551
  • 4
  • 19
  • 1
    Hey, you should check this one as it seem same as your problem http://stackoverflow.com/questions/41413776/when-i-uncomment-one-line-of-code-i-receive-this-error-http-outgoing-js359-t/41413857#41413857 – digit Jan 01 '17 at 16:58

2 Answers2

1

This Error occurs when you try to send the response more than one time. For a REST request, you can send only one response.

In your case Application.getEmailDuplicateCheck function is giving both response error and result.
So it's firing two-time first res.serverError and another res.ok

Try:

Application.getEmailDuplicateCheck(options, function(error, result) {

        console.log('Email duplicate check error', error);
        console.log('Email duplicate check result', result);

        if (error || (!result)) {
            return res.serverError(error);
        }else {
            return res.ok(result);
        }
    });
Vishnu Mishra
  • 3,683
  • 2
  • 25
  • 36
0

Instead of this:

if (error) {
    return res.serverError(error);
}

if (result) {
    return res.ok(result); /*** THIS IS LINE 180 ***/
}

Pls use that syntax:

if (error) {
    return res.serverError(error);
} else {
    if(!result) return res.notFound(); // if result is unknown

    return res.ok(result);
}

Why you got this error?

Both statements are executed, cuz probably(on 99% ) u return error and result in same time

SkyQ
  • 380
  • 2
  • 9