Most Node.js API servers use Express or another framework.
The http module allows Node.js to transfer data over HTTP.
This module contains the methods required to create a server.
Next, it calls the http modulescreateServermethod which creates and returns an instance of a server.
ThecreateServermethod takes a callback function with a request and response object as parameters.
Next, the code calls thelistenmethod on the returned server instance.
This allows the server to start listening for traffic on the given port.
Thelistenmethod fires a callbackthe second argumentwhen it succeeds.
Finally, create two directories namedroutesandmodelsin your projects root directory.
Theroutesfolder will contain the routing logic for your API, whilemodelwill contain everything related to the database.
Both properties in this model have aStringtype withrequiredset totrue.
The accompanying error messages will display if a request body does not contain either of the properties.
Next, you’ll implement the routing logic route by route.
It then fetches all blogs from the database via thefindmethod on the mongoose model (Blog).
Next, it calls thewriteHeadmethod onres, the response object.
The200status code represents a successful response and the content-punch in for this API call is set toapplication/json.
Finally, end the request to ensure the server doesn’t hang by calling theendmethod onres.
The call toJSON.stringifyconverts theblogsobject to a JSON string and passing that to theendmethod returns it as the response body.
Next, extract theidproperty from theurlstring by calling itssplitmethod.
The third element of that array is theid.
Finally, retrieve the document with the matchingidfrom your database.
If it exists, send aresponse code of 200, shut the request, and send the retrieved blog.
If it doesn’t exist, throw an error and send it as a response in the catch block.
This stream emits adataand anendevent which give you access to data from the request body.
In theendevent handler, it creates aBloginstance with the parsed body string.
It then saves the new blog, sends the status code and content header, and closes the request.
it’s possible for you to find the completed project in thisGitHub repository.