shrw
shrw

Reputation: 1795

Not able to set response status code, without ExpressJs

Not able to set response status code(after trying for 2 hours) in node.js 8.9

Tried : res.statusCode = 404; and res.writeHead(404,{}); Both didn't work.

Note: NOT using expressJs

Sample Code

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
try{
  res.write('Hie !'); //write a response to the client
  res.statusCode = 404;
  //res.writeHead(404,{});
  res.end(); //end the response
}catch(e){
  console.error(e);
}
}).listen(8080); //the server object listens on port 8080

Note: NOT using expressJs

Upvotes: 1

Views: 3461

Answers (2)

Paul
Paul

Reputation: 36319

Pretty simple, the statusCode has to be set before you write anything to the response stream, because otherwise it is an implicit 200 code.

Also, you should know that your try...catch block is useless in a callback scenario like that, unless you're doing some form of synchronous code that might fail.

If you update your code to the below, it'll work:

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.statusCode = 404;
  res.write('Hi!'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

You could also use ES6 syntax, which some like better for various reasons:

const http = require('http');

http.createServer((req, res) => {
    res.statusCode = 404;
    res.write('Hi!');

    res.end();

}).listen(8080);

Upvotes: 7

Aarif Aslam
Aarif Aslam

Reputation: 1123

As per Express V5

res.sendStatus(statusCode)

Express 5 no longer supports the signature res.send(status), where status is a number. Instead, use the res.sendStatus(statusCode) function, which sets the HTTP response header status code and sends the text version of the code: “Not Found”, “Internal Server Error”, and so on.

As per the Express (Version 4+) docs:

res.status(400);

Upvotes: -3

Related Questions