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

调用LinkedIn API GET请求遭遇预检CORS失败问题求助

问题根源

LinkedIn的授权码流程是专为服务器端应用设计的,完全不支持在前端浏览器直接调用其API接口。你现在在本地前端(http://127.0.0.1:5500)直接用fetch请求https://api.linkedin.com/v2/me,会触发浏览器的CORS安全机制,而LinkedIn的API服务器不会为前端源返回合法的CORS响应,直接导致预检请求失败。

具体原因拆解
  • 授权码流程获取的access token,仅允许服务器端发起API调用。LinkedIn的API网关会拦截前端发起的跨域请求,拒绝返回CORS相关响应头,所以浏览器发送的OPTIONS预检请求会返回非200状态码,就是你看到的错误。
  • 哪怕你手动加了Authorization头也没用——浏览器在发送实际GET请求前,会先自动发送OPTIONS预检请求确认权限,而LinkedIn根本不处理前端源的这个预检请求。
解决方案:用服务器端代理中转请求

必须通过你的后端服务来调用LinkedIn API,步骤如下:

  1. 把获取access token的逻辑移到后端(绝对不能在前端做这一步,避免token泄露)
  2. 在后端写一个代理接口,比如/api/linkedin/profile,由这个接口去调用https://api.linkedin.com/v2/me并带上access token
  3. 前端的fetch请求改为调用你自己的后端接口,这样就不存在跨域问题了(前端和后端同源,或者你可以给后端配置CORS允许你的前端源)
简化示例代码

后端(Node.js/Express)

const express = require('express');
const fetch = require('node-fetch');
const app = express();

// 后端代理接口
app.get('/api/linkedin/profile', async (req, res) => {
  try {
    // 这里的access token要从后端存储(比如会话、数据库)里取,不能硬编码
    const accessToken = '你的服务器端获取的access token';
    const linkedInRes = await fetch('https://api.linkedin.com/v2/me', {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });
    const profileData = await linkedInRes.json();
    res.json(profileData);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(3000, () => console.log('后端服务运行在3000端口'));

前端

// 调用自己的后端接口,而非直接请求LinkedIn
fetch('http://localhost:3000/api/linkedin/profile')
  .then(res => res.json())
  .then(data => console.log('用户LinkedIn信息:', data))
  .catch(err => console.error('请求失败:', err));
额外注意事项
  • 绝对不要在前端代码里写access token,一旦泄露会被恶意盗用
  • 确保你获取access token时,申请了r_liteprofile权限(这是调用/v2/me接口的必需权限)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:52:39