NodeJS POST API Tutorial
Setting up an API can be a bit confusing. An API is an Application Programming Interface, and allows third party applications to access information or store information. In this article we will be going through a simple API using Node.js and Express. You can use other web frameworks, but I find that Express
works well. If you would like a more basic tutorial, check out this tutorial.
npm version
in a console or terminal.
If you have them installed, go ahead and run the following in your console/terminal:npm i express
npm i body-parser
npm i path
index.js
for our server-side code. Let's also write our first lines in that file.
const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const port = 8000; const app = express(); if (isNaN(port)) process.exit(1); // Exits the program if the port is invalid.
app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(bodyParser.text());
http://localhost:(PORT)/
. We will use app.get()
for that and we will send our index.html file.
app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '/index.html')); // Send the index.html file. Path is used to more reliably get files from their names and the directory. });
http://localhost:(port)/
and if it receives any, it will send the index.html file, which we still have yet to create. That's our basic handler. We will implement
two more, one using app.all()
, and one using app.post()
. The app.all() function will handle ANY type of incoming requests to the specified address, which can include GET, POST, PUT, etc. We'll send simple JSON
with it. Enter the following code.
app.all('/api/helloworld/', function(req, res) { res.send({ message: "Hello World!" }); });
http://localhost:(PORT)/api/helloworld/
. It will send JSON data back. Once we are done with the index.js file, you will be able to enter the
address in your browser and view the JSON. But we're not done yet! Let's handle POST requests now. Enter the following code.
app.post('/api/helloworld/post_only', (req, res) => { res.send({ message: "Hello World! (POST)" }); });
http://localhost:(PORT)/api/helloworld/post_only
, the request will receive JSON data as a response. We aren't quite done yet. Next, we need to tell the
app to start listening. To do so, enter the following code.app.listen(port, () => { console.log(`App listening at http://localhost:${port}/`); });
<!DOCTYPE HTML> <html> <head> <title>Express.js API Tutorial Example</title> <meta charset="utf-8" /> <style> #buttonContainer { text-align: center; margin: 10px auto; } #main_text { text-align: center; } </style> <script> function sendPost() { // Define a new function var postReq = new XMLHttpRequest(); // Define a new XMLHttpRequest postReq.open("POST", 'http://localhost:8000/api/helloworld/post_only'); // Open the XMLHttpRequest postReq.send("Hi"); // Send the request postReq.onload = () => { // Will run when the request receives a response console.log(postReq.response); // Log the response } } </script> </head> <body> <h1 id='main_text'>Hello World!</h1> <div id='buttonContainer'> <button onclick='sendPost()' value='Send POST Request' id='mb'>Send POST Request</button> </div> </body> </html>
index.html
file. When you click on the button, it will send a request to your API and will log the response in the browser console.node index.js
, then navigate to http://localhost:8000/ (or whichever port you chose to use). You can add more files and paths. This just covers setting up a simple web server with Node.js. If you would like the full code, you can view it here.