【发布时间】: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