您如何使用 express/nodejs 后端从服务器重定向到客户端?

How do you redirect from server to client using express/nodejs backend?

将 MERN 堆栈与 nodejs/express 后端和 React 客户端一起使用...

从事学校项目,并尝试合并 Google 的 oAuth 2.0,以便学生可以使用学校提供的电子邮件登录。 Google 的 oAuth returns 一个查询字符串,其中包含第一个请求中的授权代码(我正在通过按钮从客户端执行此操作)。然后您必须将此授权码交换为刷新和授权令牌。我希望第一轮重定向通过服务器进行路由,以便我可以执行逻辑以仅允许使用我们高中电子邮件帐户的域登录,这可以通过 req.query.hd 执行。按照这个逻辑,在 get 请求中,从 google 重定向的服务器和用户的路由应该匹配——我们可以在哪里执行我们的逻辑,对吗?

在那里,如果你没有使用学校电子邮件域登录,我希望用户路由回客户端...并显示一条消息描述 "you did not login with the proper google acc"...怎么可能这能完成吗?

下一步(如果电子邮件域是一个通行证),在 axios 中制作一个 put req 应该处理交换,我不知道它的格式是否正确,但这是我的下一个任务要解决。如果对更顺利的过程有任何建议,我将不胜感激!只有在高中和独立学习时,如果代码看起来不合适,请随时告诉我。感谢所有帮助。

app.get("/signin/callback", (req, res, next) => {
    //declare vars from query string api return for later use
    console.log(req.query);
    let hd = req.query.hd;
    let authCode = req.query.code;

    if(hd == 'guhsd.net') {
        console.log('you are good to pass');
        next();
    } else {
        console.log('you are not good to pass')
        //REDIRECT TO REACT CLIENT ON PORT 3000 SAYING FAILED TO LOGIN 
        //BECAUSE YOU DID NOT SIGN IN WITH PROPER EMAIL ADDRESS
        //THIS IS WHERE I NEED HELP/SUGGESTIONS TO REDIRECT BACK TO CLIENT 
        res.end;
    };    

    res.send('making a post to exchange auth code for tokens')
     axios.post('https://oauth2.googleapis.com/token', {
            client_id: "a string",
            client_secret: "a string",
            code: authCode,
            grant_type: "authorization_code",
            //google handles redirect to client... react running on port:3000
            redirect_uri: "http://localhost:3000"
    });  
 });

您的代码有几次失败,您正在调用 next() 并继续调用 res.

要重定向,您可以使用 res.redirect 但首先要管理您的流程:

app.get("/signin/callback", (req, res, next) => {
    //declare vars from query string api return for later use
    console.log(req.query);
    let hd = req.query.hd;
    let authCode = req.query.code;

    if(hd !== 'guhsd.net') {
        console.log('you are not good to pass')
        // The return is fot not continue executing the controller
        return res.redirect(301, '/signing/?error=invalid_domain');
    }

    // Why you send it to the client?
    // res.send('making a post to exchange auth code for tokens')

    axios.post('https://oauth2.googleapis.com/token', {
            client_id: "a string",
            client_secret: "a string",
            code: authCode,
            grant_type: "authorization_code",
            //google handles redirect to client... react running on port:3000
            redirect_uri: "http://localhost:3000"
    })
        .then((response) => {
            console.log('Your token must to be here');
            console.log(response);
        })
        .catch((error) => {
            console.log('Error happend');
            next(error);
        });
 });