我正在创建一个 Mern 应用程序,并且正在使用 Passport.js google 身份验证 oauth20 实施身份验证。我收到 cors 错误。
这是我的代码
var GoogleStrategy = require("passport-google-oauth20").Strategy;
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback",
},
function (accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
)
);
router.get("/login/federated/google", passport.authenticate("google"));
router.get(
"/auth/google/callback",
passport.authenticate("google", {
successReturnToOrRedirect: "http://localhost:3000/",
})
);
在前端我创建了一个按钮并添加了 onclick 事件,该事件在后端调用此路由。
const handleGoogle = async () => {
const res = await axios.get(
"/api/users/login/federated/google",
{}
);
console.log(res);
};
//part of the component
<span onClick={handleGoogle} className="btn-primary">
Google
</span>
前端在 localhost 3000 上运行,后端在 localhost 5000 上运行。
单击按钮时出现此错误。请有人帮助我。
访问 XMLHttpRequest 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&client_id=388643537928-pufrfjko0kiq8f27de3ojhvve85g20 pb.apps。来自原点“http://localhost:3000”的“googleusercontent.com”(从“http://localhost:3000/api/users/login/federated/google”重定向)已被 CORS 策略阻止:无“访问控制” -Allow-Origin'标头存在于请求的资源上。
我还添加了cors
var cors = require("cors");
app.use(cors());