Baz Baz - 1 year ago 81
reST (reStructuredText) Question

Return different HTTP response codes for a REST End Point

I'm using express to serve the REST API endpoints for a mocked backend. For one of the endpoints, I'd like to be able to return different http response codes, with the other endpoints continuing to return 200. My code currently looks something like this:

var port = 32000;

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: true }) );

var setHeaders = function(req, res) {
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "http://localhost:2000");

app.get("*", setHeaders);

app.listen(port, function () {});

app.get("my/enpoint/one", function(req, res){

Answer Source

You can use res.status to set the HTTP code:

res.status(404).send('Bad Request');

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