我正在开发一个小型的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 }));
  }


我应该如何构造我的节点/表达后端,以便可以使反应侧提取正常工作?

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

最佳答案

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

编辑

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

关于node.js - React客户端获取的URL与服务器端请求的URL不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58276564/

10-09 21:21