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

JavaScript调用外部API发送GET请求时遭遇CORS错误

解决无服务器权限下的CORS跨域问题

方案1:将自定义请求头转为URL查询参数

你的请求添加了AccessKey和Token自定义头,会触发浏览器的OPTIONS预检请求,而目标服务器未配置CORS响应头导致失败。如果目标API支持通过URL查询参数传递认证信息,可以修改代码把参数拼到URL中,避免触发预检:

function displayData(){
    searchData = "";
    const accessKey = "...";
    const token = "...";
    // 把认证参数编码后拼接到URL查询字符串
    const targetUrl = `your-api-url?AccessKey=${encodeURIComponent(accessKey)}&Token=${encodeURIComponent(token)}`;
        
    const xhr = new XMLHttpRequest();
    xhr.open("GET", targetUrl, true);
    // 移除自定义请求头设置
    // xhr.setRequestHeader('AccessKey', "...");
    // xhr.setRequestHeader('Token', "..."); 
    // 无需withCredentials(除非API明确要求携带Cookie)
    // xhr.withCredentials = true; 

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                console.log('Response:', response);
            } else {
                console.error('Error:', xhr.status, xhr.statusText);
            }
        }
    };

    xhr.send();
}

方案2:搭建本地代理转发请求

如果API不支持查询参数传递认证信息,可以在本地搭建简单代理服务器,让代理去请求目标API,前端代码请求本地代理即可绕过跨域限制:

  1. 用Node.js创建proxy.js文件:
const http = require('http');
const https = require('https');

const server = http.createServer((req, res) => {
    // 替换为实际目标API地址
    const targetApi = 'your-target-api-url' + req.url;
    const proxyOptions = {
        headers: {
            'AccessKey': '...',
            'Token': '...',
            ...req.headers
        }
    };

    // 处理OPTIONS预检请求
    if (req.method === 'OPTIONS') {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', '*');
        res.writeHead(200);
        res.end();
        return;
    }

    // 转发请求到目标API
    const proxyReq = https.request(targetApi, proxyOptions, (proxyRes) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.writeHead(proxyRes.statusCode, proxyRes.headers);
        proxyRes.pipe(res, { end: true });
    });

    req.pipe(proxyReq, { end: true });
});

server.listen(3000, () => {
    console.log('代理服务器运行在 http://localhost:3000');
});
  1. 运行代理:执行node proxy.js
  2. 修改前端请求地址为本地代理:
xhr.open("GET", "http://localhost:3000", true);
// 移除自定义请求头(代理已配置)

方案3:尝试JSONP(仅API支持时可用)

如果目标API支持JSONP格式,可以用script标签发起请求绕过CORS:

function displayData(){
    const accessKey = "...";
    const token = "...";
    const targetUrl = `your-api-url?AccessKey=${encodeURIComponent(accessKey)}&Token=${encodeURIComponent(token)}&callback=handleApiResponse`;
    
    // 创建script标签加载请求
    const script = document.createElement('script');
    script.src = targetUrl;
    document.body.appendChild(script);
}

// 定义JSONP回调函数
function handleApiResponse(response){
    console.log('Response:', response);
    // 清理创建的script标签
    const script = document.querySelector('script[src*="your-api-url"]');
    if(script) document.body.removeChild(script);
}

注意:此方法要求API能返回handleApiResponse({...})格式的响应内容。


内容的提问来源于stack exchange,提问作者John Arc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:00:36