0% found this document useful (0 votes)
2 views

Express create server

This document provides a step-by-step guide on how to set up an Express.js application, including initializing a project, installing dependencies, creating a server file, defining routes for GET and POST requests, and serving static files. It explains the use of middleware, how to handle incoming requests, and how to send responses back to clients. Additionally, it covers the setup of nodemon for automatic server restarts during development.

Uploaded by

freeruncr77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Express create server

This document provides a step-by-step guide on how to set up an Express.js application, including initializing a project, installing dependencies, creating a server file, defining routes for GET and POST requests, and serving static files. It explains the use of middleware, how to handle incoming requests, and how to send responses back to clients. Additionally, it covers the setup of nodemon for automatic server restarts during development.

Uploaded by

freeruncr77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

express

Step 1. Use ‘npm init -y’ for default initialization


npm init -y

Step 2. we will install express.js dependency.


npm install express
npm i -g express // for global install

Run this command to install nodemon


npm i -D nodemon

Let me explain the changes to our package.json file. On line 7 I added


the script start
which will use our nodemon package watch our index.js file. Therefore
when I run the command npm start
in the terminal this will start our nodemon package.

Step 3: Create an app.js (or server.js) file. This will serve as the main entry
point for your application.

Use require(‘express’) to import the Express module.


Call express() to create an Express application instance.
Define the port for the application, typically 3000.
Set up a basic GET route with app.get(‘/’, (req, res) =>
res.send(‘Hello World!’)).
Use app.listen method to listen to your desired PORT and to start the
server.

const express = require('express');


// Line 1: We are bringing in the express framework and storing it in a
constant.

const app = express();


//We are initializing the express framework and saving it into another
constant.

const PORT = process.env.PORT||3000;


//Line 5: We are saving the port of our server into a constant.
The process.env.PORT is going to check your environment variables to
see if you already have a PORT defined
there if not it will use PORT 4000. In our case is going to use PORT
4000.

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);
// Line 7: We use the built-in listen method and it expects at least
one argument,
which is port number that our is located. You can pass a callback
function
as a second argument to the listen method, in this case our function is
going to log to the console
that server is running and show in which port is running on.
Step 4. to Run Application: node app.js

Step 5. Now we will set all the routes for our application.

Setting GET request route on the root URL


Use app.get() to configure the route with the path ‘/’ and a callback
function.
The callback function receives req (request) and res (response) objects
provided by Express.
req is the incoming request object containing client data, and res is
the response object used to
send data back to the client.
Use res.status() to set the HTTP status code before sending the
response.
Use res.send() to send the response back to the client. You can send a
string, object, array, or buffer.
Other response methods include res.json() for JSON objects and
res.sendFile() files.

//app.js

const express = require('express');

const app = express();


const PORT = 3000;

app.get('/', (req, res)=>{


res.status(200);
res.send("Welcome to root URL of Server");
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step 6: Now we will see how to send data to the server.

Setting route to be accessed by users to send data with post requests.


Before creating a route for receiving data, we are using an inbuilt
middleware,
Middleware is such a broad and more advanced topic so we are not going
to discuss it here,
just to understand a little bit you can think of this as a piece of
code that gets executed between the request-response cycles.
The express.json() middleware is used to parse the incoming request
object as a JSON object.
The app. use() is the syntax to use any middleware.
After that, we have created a route on path ‘/’ for post request.
const {name}, which is the syntax in ES6 to extract the given
property/es from the object.
Here we are extracting the name property that was sent by the user with
this request object.
After that, we are simply sending a response to indicate that we have
successfully received data.
If this `${} ` is looking weird to you then let me tell you that it is
the syntax in ES6
to generate strings with javascript expression in ES6. We can inject
any javascript expression inside ${}.

// app.js

const express = require('express');


const app = express();
const PORT = 3000;

app.use(express.json());
app.post('/', (req, res)=>{
const {name} = req.body;

res.send(`Welcome ${name}`);
})

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and
App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start",
error);
}
);

Step 7.to run the application: We are Accessing the route with Postman/thunder
client. It is a tool to test APIs,

Step 8. example 1

Sending a single file on a route with the sendFile() function.

We are creating a get request route on the ‘/file’ path


After that we create the absolute path by joining the path of the
current __dirname and
the name of the file we want to send and then passing it to sendFile().
The route sends the image.jpg file to the user as an HTTP response.

// app.js

const express = require('express');


const path = require('path');

const app = express();


const PORT = 3000;

app.get('/file', (req, res)=>{


res.sendFile(path.join(__dirname,'image.jpg'));
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and App
is listening on port "+ PORT)
else
console.log("Error occurred, server can't start",
error);
}
);

Example 2
Serving entire directory using middleware

First of all, we are importing an inbuilt module `path`, because later we are
going to use one of the functions
provided by this module.
We are simply mounting a middleware at the ‘/static’ route.
The static() middleware requires an absolute path so we use the path module’s
join method.
The join() method takes two parameters and joins them as a path, in NodeJS we
have a global attribute __dirname
which contains the path of the directory in which the current file exists.
We are providing that joined path to middleware so that it can start serving
the files inside that directory
on the given path.

// app.js

const express = require('express');


const app = express();
const PORT = 3000;

const path = require('path')


app.use('/static', express.static(path.join(__dirname, 'Static
Files')))

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

Step to run the application: This will be the returned response when we request
some static file from the directory
that we are serving as static. Here you can see we have received an HTML file
as a response for ‘/static/random.html’.
The same things happen when we request for ‘/static/1.jpg’.

You might also like