You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

两个Express项目无需Socket/TCP实现独立通信及身份识别需求

Got it, let's tackle this problem step by step. Since you want to stick strictly to Express without any socket-based solutions, we can use HTTP REST APIs + Session/Cookie authentication to handle client-server communication and track repeat visits. Here's a complete, working implementation:

Solution Overview
  • We'll use standard HTTP requests (the core of Express) for communication between the two apps.
  • To identify first-time vs repeat visitors, we'll use Express sessions (backed by cookies) to store a unique username for each client.
  • Both apps will have their own web routes and can run completely independently.

Step 1: Set Up the Server App (Port 3000)

This app will handle session tracking and provide a greeting API.

1.1 Initialize Dependencies

First, create a new folder, initialize the project, and install required packages:

mkdir server-app && cd server-app
npm init -y
npm install express express-session cors ejs

1.2 Server Code (app.js)

const express = require('express');
const session = require('express-session');
const cors = require('cors');
const app = express();

// Allow cross-origin requests from the client app (port 3001)
app.use(cors({
  origin: 'http://localhost:3001',
  credentials: true // Enable cookie sharing across origins
}));

// Configure session to track visitor identity
app.use(session({
  secret: 'your-secure-secret-key', // Replace with a real secret in production
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // Set to true if using HTTPS
}));

// Use EJS for rendering server's standalone page
app.set('view engine', 'ejs');

// Server's independent home page route
app.get('/', (req, res) => {
  res.render('server-home', { title: 'Server Dashboard' });
});

// API route to handle greeting logic
app.post('/api/greet', (req, res) => {
  if (req.session.username) {
    // Return welcome back message for repeat visitors
    res.json({ message: `Hey ${req.session.username}, welcome back!` });
  } else {
    // Generate a random username for first-time visitors
    const randomUsername = `Guest_${Math.floor(Math.random() * 1000)}`;
    req.session.username = randomUsername;
    res.json({ message: `Welcome! Your username is ${randomUsername}` });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

1.3 Server View (views/server-home.ejs)

Create a views folder, then add this file for the server's standalone page:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1>Server App</h1>
  <p>This app runs independently and provides greeting services to the client.</p>
</body>
</html>

Step 2: Set Up the Client App (Port 3001)

This app will have its own web interface and send requests to the server's API.

2.1 Initialize Dependencies

Create another folder, initialize the project, and install packages:

mkdir client-app && cd client-app
npm init -y
npm install express ejs node-fetch

2.2 Client Code (app.js)

const express = require('express');
const fetch = require('node-fetch');
const app = express();

// Use EJS for rendering client pages
app.set('view engine', 'ejs');

// Client's independent home page route
app.get('/', (req, res) => {
  res.render('client-home', { title: 'Client App' });
});

// Route to fetch greeting from the server
app.get('/get-greeting', async (req, res) => {
  try {
    const response = await fetch('http://localhost:3000/api/greet', {
      method: 'POST',
      credentials: 'include' // Send session cookies to the server
    });
    const data = await response.json();
    res.render('greeting-result', { message: data.message });
  } catch (error) {
    res.render('greeting-result', { message: 'Oops! Could not connect to the server. Make sure it\'s running.' });
  }
});

const PORT = 3001;
app.listen(PORT, () => {
  console.log(`Client running at http://localhost:${PORT}`);
});

2.3 Client Views

Create a views folder, then add these two files:

client-home.ejs (Client's main page)

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1>Client App</h1>
  <p>Click below to get a greeting from the server:</p>
  <a href="/get-greeting"><button>Get Greeting</button></a>
</body>
</html>

greeting-result.ejs (Displays server response)

<!DOCTYPE html>
<html>
<head>
  <title>Greeting Result</title>
</head>
<body>
  <h1><%= message %></h1>
  <p><a href="/">Go back to home</a></p>
</body>
</html>

How It Works

  1. Session Tracking: The server uses express-session to create a unique session for each client, stored in a browser cookie. When the client sends a request, the cookie is sent back to the server to verify if the visitor is returning.
  2. Cross-Origin Support: The cors middleware on the server allows requests from the client's port and enables cookie sharing, which is required for session persistence.
  3. Independence: Both apps have their own root routes (/) that render standalone pages. If the server is down, the client's home page still loads—only the greeting request will fail. If the client is down, the server's page remains fully accessible.

Testing the Setup

  1. Start the server app: node app.js (runs at http://localhost:3000)
  2. Start the client app: node app.js (runs at http://localhost:3001)
  3. Visit the client's home page: Click "Get Greeting" to receive a random username (first visit).
  4. Refresh the greeting page or click the button again: You'll see the "welcome back" message.
  5. Test independence: Stop the server, then refresh the client's home page—it loads normally. Click "Get Greeting" to see the error message.

内容的提问来源于stack exchange,提问作者Shana Alice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:45:13