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

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.

Step 1: Set up your Node.js project

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 express for the web server and node-fetch to handle HTTP requests to Leadsquared's API (you could also use axios if you prefer):
    npm install express node-fetch
    
Step 2: Build the proxy server

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}`);
});
Step 3: Important notes & setup tips
  • Never hardcode credentials! Instead of putting your Leadsquared API key/secret directly in the code, use environment variables. Create a .env file in your project root:
    LEADSQUARED_API_KEY=your-actual-api-key
    LEADSQUARED_API_SECRET=your-actual-api-secret
    PORT=3001
    
    Install dotenv to load them:
    npm install dotenv
    
    Then add this line at the top of server.js:
    require('dotenv').config();
    
  • CORS setup: Since your friend's React app will run on a different port (like 3000), enable CORS. Install the cors package:
    npm install cors
    
    Add this to your server setup:
    const 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 to http://localhost:3001/api instead of directly to Leadsquared's API.
Step 4: Run the server

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:15:04