Home > Web Front-end > JS Tutorial > How to use Node.js to develop a shopping cart function for an online mall

How to use Node.js to develop a shopping cart function for an online mall

WBOY
Release: 2023-11-08 09:18:27
Original
1299 people have browsed it

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.

  1. 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/.
  2. 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
Copy after login

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.

  1. 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
Copy after login

These dependency packages include the Express framework, Express- Session, Body Parser and EJS template engine.

  1. 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');
});
Copy after login

This code uses Express The framework creates a simple server and sets up the EJS template engine and a directory for static files.

  1. 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('/');
});
Copy after login

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.

  1. 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>
Copy after login

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.

  1. 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 });
});
Copy after login

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.

  1. 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>
Copy after login

This view template uses Displays the list of products in the shopping cart and provides a link to the checkout shopping cart.

  1. 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>
Copy after login

This view template is used Displays the page after the checkout cart and provides a payment link.

  1. 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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template