Create a Node.js server that accepts requests and creates responses and host it
ID: 3797973 • Letter: C
Question
Create a Node.js server that accepts requests and creates responses and host it on Apigee.
– The server should accept GET, POST, PUT and DELETE requests. – Any other requests coming in should be rejected.
If the server accepts a request, it should respond with information about the request.
– The server should respond with the name and value of any query parameters sent in. If no headers or query parameters are sent in, then the response should say so.
– Some headers are generated automatically, like host and user-agent. It’s fine to have these appear in the response.
If the server rejects a request, it should respond with a simple statement saying it doesn’t support the HTTP method.
The server should have four different URNs that only accept a given HTTP method, while reject the other methods.
– /gets should only accept GET requests while rejecting others.
– /posts should only accept POST requests while rejecting others.
– /puts should only accept PUT requests while rejecting others.
– /deletes should only accept DELETE requests while rejecting others.
– Any requests made to the base URL (no URN specified) should also be rejected.
Explanation / Answer
var http = require('http');
var express = require('express');
var app = express();
app.all('/', function (req, res) {
res.status(403).send('Request Rejected: no URN specified');
});
app.all('/gets', function (req, res) {
if(req.method == 'GET') {
if(Object.keys(req.query).length > 0) {
res.send(req.query);
} else {
res.send('No query parameters were sent in.');
}
} else {
res.status(403).send('Request Rejected: HTTP Method not supported.');
}
});
app.all('/posts', function (req, res) {
if(req.method == 'POST') {
if(Object.keys(req.query).length > 0) {
res.send(req.query);
} else {
res.send('No query parameters were sent in.');
}
} else {
res.status(403).send('Request Rejected: HTTP Method not supported.');
}
});
app.all('/puts', function (req, res) {
if(req.method == 'PUT') {
if(Object.keys(req.query).length > 0) {
res.send(req.query);
} else {
res.send('No query parameters were sent in.');
}
} else {
res.status(403).send('Request Rejected: HTTP Method not supported.');
}
});
app.all('/deletes', function (req, res) {
if(req.method == 'DELETE') {
if(Object.keys(req.query).length > 0) {
res.send(req.query);
} else {
res.send('No query parameters were sent in.');
}
} else {
res.status(403).send('Request Rejected: HTTP Method not supported.');
}
});
app.all('*', function (req, res) {
res.status(403).send('Request Rejected: URN does not support the HTTP Method.');
});
var server = app.listen(8080, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Node.js server listening at http:%s:%s', host, port)
});