API is a module for easily providing several RESTful APIs on a single
server. It inherits all methods from http.Server
.
test.js
:
// Use the HTTP version
var api = require('api')('http'),
msg = 'Hello World!';
var server = new api.Server();
server.listen(1337, '127.0.0.1');
function error404(res) {
res.writeHead(404);
res.end('Not found.\n');
};
// Listen for regular requests and end with an 404 error.
server.on('regularRequest', function(req, res) {
error404(res);
});
// Listen for requests to /hello-world.
server.on('/hello-world', function(req, res) {
if (req.method == 'GET') {
res.writeHead(200);
res.end(msg+'\n');
} else if (req.method == 'POST') {
res.writeHead(200);
msg = '';
// Update the message
req.on('data', function(chunk) {
msg += chunk;
});
// After the POST request has ended, end with the message.
req.on('end', function() {
res.end('Successfully changed message to "'+msg+'".\n');
});
} else {
error404(res);
}
});
Test it.
$ node test.js
$ curl http://localhost:1337/hello-world
Hello World!
$ curl -d foobar http://localhost:1337/hello-world
Successfully changed message to "foobar".
$ curl http://localhost:1337/hello-world
foobar
$ curl http://localhost:1337/
Not Found.
You can use HTTP or HTTPS if you want by providing the argument when including the package.
For HTTP do require('api')('http')
.
For HTTPS do require('api')('https')
.
If you encounter any bugs or issues, feel free to open an issue at github.
This package is licensed under the MIT license.