32

How can I send status and message in express 4.14?

For: res.sendStatus(200);

I get OK on my browser but I want it to display a custom message such as: Success 1

res.sendStatus(200);
res.send('Success 1');

Error:

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

If I do this:

res.status(200).send(1);

Error:

express deprecated res.send(status): Use res.sendStatus(status) instead

Any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

79

You can use:

res.status(200).send('some text');

if you want to pass number to the send method, convert it to string first to avoid deprecation error message.

the deprecation is for sending status directly inside send.

res.send(200) // <- is deprecated

BTW - the default status is 200, so you can simply use res.send('Success 1'). Use .status() only for other status codes

Dima Grossman
  • 2,800
  • 2
  • 21
  • 26
  • 2
    you will get `express deprecated res.send(status): Use res.sendStatus(status) instead` see my edit above thanks. – Run Jul 02 '16 at 08:22
  • 1
    Please read my response, It will only happend when passing number to send() – Dima Grossman Jul 02 '16 at 08:25
  • 1
    res.status(304).send("No changes made"); returns only the status code and not the message. Also, res.status(200).send("Not modified") works nicely, any idea why? – metamemelord Jun 04 '18 at 15:03
9

You shouldn't be getting that last error if you're using that exact code:

res.status(200).send('Success 1')

My guess is that you're not using the string "Success 1" but a numerical variable or value instead:

let value = 123;
res.status(200).send(value);

That would trigger the warning. Instead, make sure that value is stringified:

let value = 123;
res.status(200).send(String(value));  
robertklep
  • 198,204
  • 35
  • 394
  • 381