【问题标题】:CORS error on Linkedin oauth/v2/accessToken API from frontend来自前端的 Linkedin oauth/v2/accessToken API 上的 CORS 错误
【发布时间】:2021-11-14 03:52:50
【问题描述】:

我正在尝试访问 Linkedin accessToken API,但在 react js(前端)中总是遇到 CORS 错误。在 URL 栏中或通过邮递员直接点击时,Samething 可以工作。 这是我得到的错误:

Access to fetch at 'https://www.linkedin.com/oauth/v2/accessToken' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的代码是:

const queryParams = querystring.stringify({
  redirect_uri: process.env.REACT_APP_LINKEDIN_REDIRECT_URI,
  client_id: process.env.REACT_APP_LINKEDIN_CLIENT_ID,
  client_secret: process.env.REACT_APP_LINKEDIN_CLIENT_SECRET,
  grant_type: 'authorization_code',
  code: code,
});
const headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
};


const response = await fetch(`https://www.linkedin.com/oauth/v2/accessToken`, {
  method: 'POST',
  headers: headers,
  body: queryParams,
});

`

【问题讨论】:

标签: javascript reactjs cors frontend linkedin-api


【解决方案1】:

API 响应不包含 Access-Control-Allow-Origin 标头,因此您的浏览器正在禁止对这些 API 的请求。

你有两个选择:

  1. 使用2-legged OAuth flow在后端获取访问令牌
  2. 或使用3-legged OAuth flow 要求您将用户的浏览器重定向到Linkedin 的网站

从安全角度来看,你should not distribute the client secret in HTML/JS files

【讨论】:

    【解决方案2】:

    Linkedin API 不允许使用 CORS 标头“Access-Control-Allow-Origin”来自本地主机等位置的请求。 https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

    如果你真的需要它,你可以随时拥有你的代理服务器或使用类似https://cors-anywhere.herokuapp.com/的东西。

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2019-06-05
      • 1970-01-01
      • 2021-06-05
      • 2018-03-04
      相关资源
      最近更新 更多