Node.js新手咨询:对接React转发RESTful API至Leadsquared.com
Hey there! Since you're new to Node.js, let's walk through building this request proxy server step by step. It's simpler than it sounds—we'll just create a middle layer that takes requests from your friend's React UI, forwards them to Leadsquared's API, and sends the response right back.
First, let's get the basics in place:
- Create a new folder for your project, then open it in your terminal.
- Initialize a Node.js project:
npm init -y - Install the necessary dependencies. We'll use
expressfor the web server andnode-fetchto handle HTTP requests to Leadsquared's API (you could also useaxiosif you prefer):npm install express node-fetch
Create a file named server.js (or whatever you want to call it) with the following code. I've added comments to explain each part:
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const PORT = process.env.PORT || 3001; // Middleware to parse JSON request bodies (since React will send JSON) app.use(express.json()); // Replace these with your actual Leadsquared API credentials const LEADSQUARED_API_KEY = process.env.LEADSQUARED_API_KEY || 'your-api-key'; const LEADSQUARED_API_SECRET = process.env.LEADSQUARED_API_SECRET || 'your-api-secret'; const LEADSQUARED_BASE_URL = 'https://api.leadsquared.com/v2'; // A generic proxy endpoint that handles all HTTP methods app.all('/api/*', async (req, res) => { try { // Extract the path from the request (e.g., if React calls /api/Leads, we use /Leads for Leadsquared) const apiPath = req.path.replace('/api', ''); // Build the full URL for Leadsquared's API const targetUrl = `${LEADSQUARED_BASE_URL}${apiPath}`; // Prepare options for the request to Leadsquared const fetchOptions = { method: req.method, headers: { // Pass along any headers from React, plus add Leadsquared auth headers ...req.headers, 'Authorization': `Basic ${Buffer.from(`${LEADSQUARED_API_KEY}:${LEADSQUARED_API_SECRET}`).toString('base64')}`, 'Content-Type': 'application/json' } }; // If it's a POST/PUT/PATCH request, include the request body from React if (['POST', 'PUT', 'PATCH'].includes(req.method)) { fetchOptions.body = JSON.stringify(req.body); } // Forward the request to Leadsquared const response = await fetch(targetUrl, fetchOptions); // Get the response data from Leadsquared const responseData = await response.json(); // Send the response back to React, preserving the status code from Leadsquared res.status(response.status).json(responseData); } catch (error) { // Handle any errors (e.g., network issues, invalid API credentials) console.error('Proxy error:', error); res.status(500).json({ error: 'Failed to forward request to Leadsquared API' }); } }); // Start the server app.listen(PORT, () => { console.log(`Proxy server running on port ${PORT}`); });
- Never hardcode credentials! Instead of putting your Leadsquared API key/secret directly in the code, use environment variables. Create a
.envfile in your project root:
InstallLEADSQUARED_API_KEY=your-actual-api-key LEADSQUARED_API_SECRET=your-actual-api-secret PORT=3001dotenvto load them:
Then add this line at the top ofnpm install dotenvserver.js:require('dotenv').config(); - CORS setup: Since your friend's React app will run on a different port (like 3000), enable CORS. Install the
corspackage:
Add this to your server setup:npm install corsconst cors = require('cors'); app.use(cors()); - Testing: Test the proxy first with tools like Postman. Send a request to
http://localhost:3001/api/Leads(or any Leadsquared endpoint you need) to confirm it returns the correct response. Then your friend can update their React app to send requests tohttp://localhost:3001/apiinstead of directly to Leadsquared's API.
Start your proxy server with:
node server.js
For auto-reloads during development, install nodemon:
npm install -g nodemon nodemon server.js
That's it! This server handles all request forwarding and response passing without needing a database. If you hit snags with specific Leadsquared endpoints or React integration, feel free to dig into the error logs and adjust the code as needed.
内容的提问来源于stack exchange,提问作者gagan

