npm init
command and follow the prompts to fill in the details.npm install express --save
command. This will download and install the latest version of Express.js and add it as a dependency to your project.app.js
, and import the Express.js module at the top of the file using the require()
function. You can also create a new folder named routes
and add separate JavaScript files for different parts of your website, like home.js
, about.js
, etc., to keep the code organized.express()
function and storing the resulting object in a variable, say app
.app.use(express.static('public'))
to serve static files from a folder named public
in your project directory, or app.use(express.json())
to parse incoming JSON data from HTTP requests.app.get()
, app.post()
, app.put()
, or app.delete()
methods, based on the HTTP method used to send the request. For example:app.get('/', (req, res) => {
res.send('Welcome to my Express website!');
});
This will respond with a simple text message when the root URL is accessed using a GET method.
8. Finally, start the Express.js server by calling the app.listen()
method and passing it the port number and hostname (if any) to listen on. For example:
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This will start the server and display a message in the console when it is ready to receive requests. 9. You can now open a web browser and navigate to http://localhost:3000 to see your website in action. You can also add more routes and functionalities to your website by editing the app object in your JavaScript files.
Asked: 2021-05-21 11:00:00 +0000
Seen: 17 times
Last updated: Apr 10 '22