Express create server
Express create server
Step 3: Create an app.js (or server.js) file. This will serve as the main entry
point for your application.
Step 5. Now we will set all the routes for our application.
//app.js
// app.js
app.use(express.json());
app.post('/', (req, res)=>{
const {name} = req.body;
res.send(`Welcome ${name}`);
})
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
// app.js
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
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’.