NodeJS has actually encapsulated all of the hard work. A simple server that will wait for HTTP GET statements.
This simple server program has a lot of functionality. It is an example of three different endpoints that can be called. The /hello and /goodbye are pretty obvious and simply return a json message to the caller.
const express = require('express') let app = express() app.use(express.json()); app.get('/hello', (request, response) => { response.json({ "message": "hello world" }); }); app.get('/goodbye', (request, response) => { response.status(200).send("goodbye world"); }); app.get('/x/:id', (request, response) => { response.status(200).send(request.params.id ); }); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`listing on port ${port}` ));
The third endpoint is a bit more interesting as it allows you to pass in a parameter and easily as part of the URL. This particular example might be good for retrieving a value (ie book) by the code that is passed in. Because this is a service and not a web server it is only returning a value and not a webpage. But this is pretty useful as a backend server for your website.
Just as important as the ability to get information it is important to be able to pass in a complex structure.
app.post('/newitem', (request, response) => { let body = request.body; console.log("body of post") console.log(body); var keys = Object.keys(body); for (i in keys) console.log(i,keys[i],body[keys[i]]); response.status(200).send(request.params.id ); });
This example post endpoint allows us to pass in any structure and print it out to the console.
In my next post I will expand on this for other features that might be useful.