


How to use Node.js to develop a shopping cart function for an online mall
How to use Node.js to develop the shopping cart function of an online mall
In today's Internet era, e-commerce has become one of the main ways for people to shop. A complete shopping cart function is very important for online shopping malls. It can provide users with a convenient shopping experience and improve user conversion rates. This article will introduce how to use Node.js to develop a shopping cart function for an online mall and provide specific code examples.
- Environment preparation
First, make sure that Node.js and npm are installed on your computer. You can download and install the latest Node.js version from the official website https://nodejs.org/. - Create Project
Open your command line tool, go to a directory you like, and execute the following command to create a new Node.js project:
mkdir online-store cd online-store npm init -y
These The command will create a folder named online-store and generate a package.json file in it to record the project's dependencies and other related information.
- Installing dependencies
Execute the following command in the project root directory to install the dependency packages we need:
npm install express express-session body-parser ejs --save
These dependency packages include the Express framework, Express- Session, Body Parser and EJS template engine.
- Create server
Create a file named app.js in the project root directory and add the following code:
const express = require('express'); const session = require('express-session'); const bodyParser = require('body-parser'); const app = express(); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(session({ secret: 'my-secret-key', resave: false, saveUninitialized: true })); app.listen(3000, () => { console.log('Server is running on port 3000'); });
This code uses Express The framework creates a simple server and sets up the EJS template engine and a directory for static files.
- Create routes
Add the following code in the app.js file to create shopping cart-related routes:
app.get('/', (req, res) => { res.render('index', { message: req.session.message }); }); app.post('/add-to-cart', (req, res) => { // 处理添加商品到购物车的逻辑 }); app.get('/cart', (req, res) => { // 显示购物车页面 }); app.get('/checkout', (req, res) => { // 结算购物车中的商品 }); app.get('/success', (req, res) => { req.session.message = '订单支付成功!'; res.redirect('/'); });
This code defines four routes, They are used to display the home page, process the logic of adding products to the shopping cart, display the shopping cart page, and check out the products in the shopping cart.
- Writing View Template
Create a folder named views in the project root directory and create a file named index.ejs in it. Add the following code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Online Store</title> </head> <body> <h1>Welcome to Online Store!</h1> <% if (message) { %> <p><%= message %></p> <% } %> <form action="/add-to-cart" method="post"> <input type="hidden" name="product" value="Product A"> <button type="submit">Add to Cart</button> </form> <a href="/cart">View Cart</a> <a href="/checkout">Checkout</a> </body> </html>
This view template is used to display the homepage and provides links to add items to the shopping cart, view the shopping cart, and check out the shopping cart.
- Implement the shopping cart function
Add the following code in the app.js file to implement the shopping cart function:
app.post('/add-to-cart', (req, res) => { const product = req.body.product; req.session.cart = req.session.cart || []; req.session.cart.push(product); res.redirect('/'); }); app.get('/cart', (req, res) => { const cart = req.session.cart || []; res.render('cart', { cart }); }); app.get('/checkout', (req, res) => { const cart = req.session.cart || []; req.session.cart = []; res.render('checkout', { cart }); });
This code adds products through requests Go to the shopping cart and display the items in the shopping cart on the shopping cart page and checkout page.
- Writing shopping cart view
Create a file named cart.ejs in the views folder and add the following code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Shopping Cart</title> </head> <body> <h1>Your Shopping Cart</h1> <% if (cart.length > 0) { %> <ul> <% cart.forEach(product => { %> <li><%= product %></li> <% }) %> </ul> <% } else { %> <p>Your shopping cart is empty.</p> <% } %> <a href="/checkout">Checkout</a> </body> </html>
This view template uses Displays the list of products in the shopping cart and provides a link to the checkout shopping cart.
- Writing Checkout View
Create a file named checkout.ejs in the views folder and add the following code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Checkout</title> </head> <body> <h1>Checkout</h1> <% if (cart.length > 0) { %> <ul> <% cart.forEach(product => { %> <li><%= product %></li> <% }) %> </ul> <p>Thank you for your order!</p> <% } else { %> <p>Your shopping cart is empty.</p> <% } %> <a href="/success">Pay Now</a> </body> </html>
This view template is used Displays the page after the checkout cart and provides a payment link.
- Run the project
Enter the project root directory in the command line tool and execute the following command to start the server:
node app.js
Then visit http:// in the browser /localhost:3000 , you will see a simple online mall page. You can click the "Add to Cart" button to add items to the shopping cart and view the items in the shopping cart on the shopping cart page and checkout page.
Summary
This article introduces how to use Node.js to develop a shopping cart function for an online mall. By using the Express framework, we can quickly build a simple server and use the EJS template engine to render the view. The shopping cart function is implemented using Express-Session, and node sessions are used to store shopping cart data. I hope this article will help you understand how to use Node.js to develop the shopping cart function of an online mall.
The above is the detailed content of How to use Node.js to develop a shopping cart function for an online mall. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Node.js is suitable for the following project types: Network and server applications Event-driven applications Real-time applications Data-intensive applications Command-line tools and scripts Lightweight microservices
