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

在Vercel服务中使用XMLHttpRequest出现502错误的求助

Fixing 502 Bad Gateway When Using XMLHttpRequest in Vercel Serverless Functions

The root cause here is straightforward: XMLHttpRequest is a browser-only API, and Vercel's Serverless Functions run in a Node.js environment where this object doesn't exist. That missing reference is triggering an uncaught error, which leads directly to the 502 Bad Gateway response.

Let's fix this by using tools designed for Node.js server-side code—either the built-in HTTP modules or a popular third-party client.


Solution 1: Use Node.js's Built-in https Module

Node.js comes with native http and https modules for making server-side HTTP requests. Here's how to rewrite your function with https.get:

const https = require('https');

module.exports = (req, res) => {
  const { name = "World" } = req.query;
  // Replace these with your actual API details
  const url = "YOUR_TARGET_API_URL";
  const authKey = "YOUR_AUTHORIZATION_KEY";

  const requestOptions = {
    headers: {
      'Authorization': authKey
    }
  };

  https.get(url, requestOptions, (apiResponse) => {
    let responseData = '';

    // Collect chunks of the API response
    apiResponse.on('data', (chunk) => {
      responseData += chunk;
    });

    // Process the full response once it's received
    apiResponse.on('end', () => {
      if (apiResponse.statusCode === 200) {
        try {
          const parsedData = JSON.parse(responseData);
          const svgResult = `
            <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
              <text x="0" y="15" fill="red">${JSON.stringify(parsedData)}</text>
            </svg>
          `;
          res.writeHead(200, { "Content-Type": "image/svg+xml" });
          res.end(svgResult);
        } catch (parseError) {
          // Handle JSON parsing failures
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.end('Failed to parse API response data');
        }
      } else {
        // Handle non-success status codes from the target API
        res.writeHead(apiResponse.statusCode, { "Content-Type": "text/plain" });
        res.end(`API returned error: ${apiResponse.statusCode}`);
      }
    });
  }).on('error', (requestError) => {
    // Handle network or connection errors
    res.writeHead(500, { "Content-Type": "text/plain" });
    res.end(`Failed to connect to target API: ${requestError.message}`);
  });
};

Solution 2: Use axios (Simpler Promise-Based Approach)

If you prefer cleaner, promise-based syntax, use axios—a widely adopted HTTP client. First, install the dependency in your project:

npm install axios

Then rewrite your function with async/await for easier async flow handling:

const axios = require('axios');

module.exports = async (req, res) => {
  const { name = "World" } = req.query;
  const url = "YOUR_TARGET_API_URL";
  const authKey = "YOUR_AUTHORIZATION_KEY";

  try {
    const apiResponse = await axios.get(url, {
      headers: {
        'Authorization': authKey
      }
    });

    const svgResult = `
      <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
        <text x="0" y="15" fill="red">${JSON.stringify(apiResponse.data)}</text>
      </svg>
    `;
    res.writeHead(200, { "Content-Type": "image/svg+xml" });
    res.end(svgResult);
  } catch (error) {
    // Catch all errors (network issues, bad API responses, etc.)
    const statusCode = error.response?.status || 500;
    res.writeHead(statusCode, { "Content-Type": "text/plain" });
    res.end(`Request failed: ${error.message}`);
  }
};

Critical Tips to Prevent Future 502 Errors

  • Always handle errors: If any step (API request, JSON parsing, SVG generation) fails, send a clear HTTP response to the client. Failing to do this will leave Vercel's server hanging, triggering a 502.
  • Use environment variables: Store sensitive values like authKey in Vercel's environment variables instead of hardcoding them—this is more secure and flexible.
  • Validate inputs: Ensure your url and authKey variables are properly defined before making the request.

内容的提问来源于stack exchange,提问作者Will Rowe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:22:29