Atlante Avila Atlante Avila - 1 year ago 83
JSON Question

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.urlencoded({ extended: true }));

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.

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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download