This is a stupidly simple short guide full of pictures to create and start a Node web service with an Express API. This is the first article in a series using Node, Express, MongoDB, and React to teach the process of creating a simple full stack application.
First, I'm going to show the complete file. I will break down each line to the best of my ability.
Now let's begin:
Inside of command prompt, go to the folder you will be building the app in. Type the command, "npm init". You will be asked a series of questions. You can push the "enter" key to answer all the questions and "yes" to the last one.
This process creates a package.json file.
Inside of command prompt, type the command "npm install express". This will install the "Express" framework used to create an API on Node.
Finally, time to code. Create an "app.js" file in the same folder containing the package.json file. In the "app.js" file, write:
Line 1 is the standard way to import a module into the application. AKA, allows you to use that software. Line 2 is creating an Express object or application in a variable called "app".
Line 3 is setting up a port for the server to listen for API calls. Ignore the "process.env.PORT" section, this is use set the port to an environment variable. The important part is the "3000". This allows you to view the app at http://localhost:3000/ when we are finished.
Let's quickly break down lines 5–7. This is an API call used by a client to ask the server for a resource. Line 5 states that if a client asks for the root directory of this service, a request and response objects is created. The request is from the client to convey additional information to the server like a query or id. The response is from the server to the client to return the requested information/resource. Line 6 is the response from the server sending text back to the client.
Quick break-down of lines 9–11, on line 9 the Express application ("app") is listening on the port for incoming HTTP requests (aka, API calls). Line 10 isn't really needed but during development it helps to know if something works.
Step 7. DONE, let's test drive this bad baby
Inside of command prompt, type "node app.js". You should see the console.log statement from line 10 in the command prompt letting you know it works. Now in your browser, type http://localhost:3000/. You will see some magic that you created.