【问题标题】:React Client-side fetched URL doesn't match server-side requested URLReact 客户端获取的 URL 与服务器端请求的 URL 不匹配
【发布时间】:2020-02-05 03:54:44
【问题描述】:

我正在开发一个小型 nodejs-express-react 应用程序。我正在向 Google Analytics Management API 服务器端发送请求,然后尝试从客户端获取响应。它不起作用,因为提取的状态代码是Status Code: 405。但是,我看到获取的 URL 与请求的 URL 不同。我不明白到底出了什么问题。

我正在获取/auth/google/callback,但根据网络信息并查看错误请求的url是https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&client_id=XXXXXXX-XXXXXXX.apps.googleusercontent.com

这是完整的错误:

Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&client_id=XXXXXXXX-XXXXXXXX.apps.googleusercontent.com' (redirected from 'http://localhost:5000/auth/google/callback') from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

我在服务器端有这个:

app.get(
    "/auth/google",
    passport.authenticate("google", { scope: ['Profile','https://www.googleapis.com/auth/analytics.readonly'] })
);

app.get(
    "/auth/google/callback",
    passport.authenticate("google", { failureRedirect: "/error", session: false }),
    function(req, res) {
        var token = req.user.token;
    request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token,  
function (error, response, body) {
  console.log(JSON.parse(body).items);
res.send({data:JSON.parse(body).items})
});
    }
);

这在客户端:

  componentDidMount() {
    fetch('/auth/google/callback',    {
          method: 'GET',
          withCredentials: true,
          headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'},
          credentials: 'same-origin'
      })
      .then(res => res.json())
      .then(user => this.setState({ data: data }));
  }

我应该如何构建我的 node/express 后端,以便让 react-side fetch 正常工作?

编辑:我在标题中添加了'Access-Control-Allow-Origin': '*',但仍然出现错误。

【问题讨论】:

    标签: node.js reactjs express passport.js google-authentication


    【解决方案1】:

    fetch('/auth/google/callback' 需要完整的 URL(例如 https://localhost:8080/auth/google/callback

    编辑

    headers: {
        'Content-Type': 'application/json', 
        'Access-Control-Allow-Origin': '*'
    }
    

    【讨论】:

    • 如果您使用 Postman 进行测试,您的服务器方法是否有效?
    • 是的。如果我直接到达 /auth/google,我可以看到来自 API 的响应
    • 看起来客户是问题所在,让我们专注于此
    • 还有“获取的 URL 与请求的 URL 不一样”是什么意思?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多