Atlante Avila
Atlante Avila

Reputation: 1488

Node, how can I send response headers on a node/express app?

I have a basic server. One of my tests that I need to pass is to send the response header of 200. I added the code for the server as it is now. But not sure how to send response headers. Thanks for any help you may be able to provide!

var express = require('express');
var bodyParser = require('body-parser');
var Users = require('./models/users');

var app = express();
app.use(bodyParser.json());

// YOUR CODE BELOW
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var router = express.Router();

// middleware for all requests:
router.use(function(req, res, next){
  console.log('we out here babay!');
  // get to the next route and ensures we don't stop here.
  next();
})

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

app.use('/api', router);

// Do not touch this invocation of the `listen` method
app.listen('8888', function () {
  console.log('listening on 8888');
});

// Do not touch the exports object
module.exports = app;

Upvotes: 0

Views: 189

Answers (1)

Rayon
Rayon

Reputation: 36609

Use res.status(CODE) method!

res.status(200).json({ message: 'hooray! welcome to our api!' });

As highlighted in comments by jfriend00, default status code is 200 so any regular response will already be 200 but for other codes like 500 or 404, if your client side is considering it while reading the response, you can use res.status() method.

Upvotes: 1

Related Questions