Creating an Express app involves several steps. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Below is a step-by-step guide to creating a basic Express app:
Create a Project Directory:
mkdir my-express-app cd my-express-app
Initialize a New Node.js Project:
npm init -y
This will create a package.json file with default settings.
Install Express using npm:
npm install express
Set Up the Basic Server:
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
Run your Express app using Node.js:
node app.js
Open your browser and navigate to http://localhost:3000. You should see "Hello World!" displayed.
You can add more routes and middleware to your Express app. For example:
Add a Route:
app.get('/about', (req, res) => { res.send('About Page'); });
Use Middleware:
const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.post('/data', (req, res) => { const data = req.body; res.send(`Received data: ${JSON.stringify(data)}`); });
For larger applications, it's a good practice to organize your code into separate modules.
Create a Routes Directory:
mkdir routes
Create a Route File: Create a file named index.js inside the routes directory.
const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('Hello World!'); }); router.get('/about', (req, res) => { res.send('About Page'); }); module.exports = router;
Update app.js to Use the Route File:
const express = require('express'); const app = express(); const port = 3000; const indexRouter = require('./routes/index'); app.use('/', indexRouter); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
For configuration settings, use environment variables.
Install dotenv Package:
npm install dotenv
Create a .env File:
PORT=3000
Update app.js to Use dotenv:
require('dotenv').config(); const express = require('express'); const app = express(); const port = process.env.PORT || 3000; const indexRouter = require('./routes/index'); app.use('/', indexRouter); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
That's it! You've created a basic Express app. You can expand this further by adding more routes, middleware, and other features as needed.
The above is the detailed content of Express for Beginners: Create Your First Web App Today. For more information, please follow other related articles on the PHP Chinese website!