Node.js Web服务跳转实现及跨应用交互技术咨询
Absolutely, this solution is fully feasible! Let’s walk through the implementation for both Site A and Site B, with a focus on the Node.js redirect logic and passing data to your Angular frontend.
Site A Implementation
Site A can easily send a request to Site B’s REST API using vanilla browser JavaScript (like fetch) or libraries like axios. Here’s a straightforward example:
// Site A frontend code (runs when the page loads) document.addEventListener('DOMContentLoaded', () => { // Send POST request to Site B's endpoint fetch('http://your-siteb-backend-url/handle-request', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: 'Site A request' }) }) .then(response => { // Automatically follow the redirect returned by Site B window.location.href = response.url; }) .catch(error => console.error('Request failed:', error)); });
If you specifically need to use SOAP instead of REST, you can use browser-compatible SOAP libraries (though REST is simpler for this use case).
Site B (Node.js + Express) Implementation
We’ll use Express.js (the most popular Node.js web framework) to build Site B’s backend, handle incoming requests, manage redirects, and pass data to your Angular app.
Step 1: Set Up the Project
First, initialize your Node.js project and install dependencies:
npm init -y npm install express cors
Step 2: Backend Logic for Redirects
Create a server.js file with the following code:
const express = require('express'); const cors = require('cors'); const app = express(); const port = 3000; // Allow cross-origin requests from Site A (restrict to Site A's domain in production!) app.use(cors({ origin: 'http://your-sitea-url' })); // Parse JSON request bodies app.use(express.json()); // Endpoint to handle requests from Site A app.post('/handle-request', (req, res) => { const incomingMessage = req.body?.message; if (incomingMessage === 'Site A request') { // Redirect to Site B's Angular app, passing "Site A" via query parameter res.redirect(`http://www.siteB.com?visitor=Site%20A`); } else { // Redirect to Google if the request doesn't match res.redirect('https://www.google.com'); } }); app.listen(port, () => { console.log(`Site B backend running on port ${port}`); });
Step 3: Retrieve Data in Angular
On your www.siteB.com Angular app, you can grab the query parameter and display the welcome message:
// In your Angular component (e.g., app.component.ts) import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-root', template: `<h1>{{ welcomeMessage }}</h1>` }) export class AppComponent implements OnInit { welcomeMessage = ''; constructor(private route: ActivatedRoute) {} ngOnInit(): void { // Get the "visitor" parameter from the URL const visitor = this.route.snapshot.queryParamMap.get('visitor'); if (visitor) { this.welcomeMessage = `Welcome ${visitor}`; } } }
Key Notes
- Security: In production, restrict the CORS origin to only Site A’s domain to prevent unauthorized requests.
- Redirect Behavior: Express’s
res.redirect()sends a302 Foundstatus code, which tells the browser to navigate to the new URL automatically. - Data Passing: Query parameters are a simple, safe way to pass this kind of public data to your Angular app. For sensitive data, consider using session cookies or JWT tokens instead.
内容的提问来源于stack exchange,提问作者Alex Sim

