Posts on this Category



Node.js: How to make POST Requests with JSON data

In this post I’m going to show you how to work with POST requests, I’ll give you an example as simple as possible. First I’ll create the Nodejs app to receive the requests, then I’ll show you how to make the requests from the frontend.

We’re going to be using Expressjs, it’s a very popular npm package, you probably already heard of it, but if you don’t, just click here to see the instructions on how to create your project. You can also add express to an existing project via npm, but in this case you’ll have to add the body-parser as well.

Express creates a basic project structure for us, but most of it will not be used in this example, so I’m going to open my app.js and get rid of almost everything, this is the minimum we need to create requests routes:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
<pre lang="javascript">
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
 
module.exports = app;

Now let’s create our first route, I’m putting it at the end, right above the module.exports line:

app.post('/test', (request, response) => {
   console.log(request.body);
   response.json(request.body);
});

Here I’m using the express post function to create the route, it receives the path, which in this case is /test and a callback function to handle the request. Note that this function has two parameters, request and response. The first contains the JSON data passed by the client, it can be accessed through the attribute body. The second is where we put the result, so the client can receive it when the request completes.

In this example, after receiving a request the server will print the JSON dataset sent by the client and then send back the exact same data.

Ok, we’re done with the server-side now, let’s see how to make requests with the Fetch API on the frontend.

var data = [{"username": "dmccreadie0"}, 
   {"username": "bwillerson1"}, 
   {"username": "fteese2"}, 
   {"username": "dsummerell3"}];
 
fetch('http://localhost:3000/test', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {'Content-Type': 'application/json'}
}).then(response => { 
  return response.json(); 
}).then(data => { 
  alert(JSON.stringify(data));
}).catch(err => {
    alert(err);
});

The variable data is a simple JSON dataset I’ve created to use as an example. When making a request with fetch() we have to pass the URL, which in this case is http://localhost:3000/test, and an object containing the request options (method, body and header). To include the JSON data in the request we have to convert it to string and assign it to the body attribute, this way the server will be able to retrieve this data as we saw before.

Lastly, let’s see how to get the data sent by the server. The function then() allows us to add a callback that handles the response. To retrieve our data we just have to use the function json(). In this example I’m just extracting the JSON from the response and showing it to the user with an alert dialog.

That’s pretty much it guys, of course there’s much more we can do here, it’s a big topic, but as I said this is just a basic example. If you have any doubts don’t hesitate to ask in the comments.

Express.js: How to Change the Default Port

By default Express uses port 3000, but sometimes this port is already been used by another application, so you can either close the other application or change the port. In this short tutorial I’m going to show you how easy it is to change the port.

First let’s open the bin/www file and locate this code:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

Here is where we can configure which ports to use, all you have to do is to replace the number 3000 by another port number. After that your application will not be using port 3000 anymore.

Alternatively you can also configure the port on your app.js:

var app = express();
app.listen(4000);

As you can see I’ve just added the app.listen(4000) line, this will make the application also listen on port 4000, but the difference is that this method won’t make your app stop using port 3000.

It’s up to you to decide which method works better for you, If you have any doubts please let me know in the comments.

Node Express Error: Cannot find module ‘serve-favicon’

This error means you don’t have the module ‘serve-favicon’ installed on your project, here is the full error:

Error: Cannot find module 'serve-favicon'
    at Function.Module._resolveFilename (module.js:542:15)
    at Function.Module._load (module.js:472:25)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\project\a2-notifications\app.js:3:15)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! notifications@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to in
stall?

Buf if you are getting this error the ‘serve-favicon’ is probably not the only module missing. My guess is that you forgot to install the dependencies before running your project with npm start. Try executing npm install first, this command will download all the dependencies for you, after that your problem should be solved.

Creating a NodeJS project with Express

Express is one of the most popular npm packages out there, it’s basically a NodeJS web application framework that provides lots of functionalities and helps you to manage everything and organize your app into MVC on the back-end, and it’s very easy to get started with.

To use Express you first need to have NodeJS installed (obviously), if you don’t have it yet click here and download the appropriate version for your OS. With nodejs installed you can now create your your project and start using express, in this tutorial I’m just going to cover how to create the project, but in the future I’ll probably write more about it.

Express has a tool called express-generator that is used to create the project’s basic structure, to install it just use the command:

npm install express-generator -g

Now that we’ve installed it globally we’re ready to create the project, open your terminal and navigate to the folder where you want to put your project, then simply run the command:

express myFirstExpressApp

Done! Now you have a folder called myFirstExpressApp (or any other name you’ve chosen), if you go inside it you’ll see the project files and the following folder structure:

Express Basic Project Structure
Express Basic Project Structure