首页 > 解决方案 > 服务器和客户端如何通信?

问题描述

如何从客户端向服务器发送请求,客户端是 next.js,服务器是 express.js。

我正在尝试实现 google auth,在服务器上我有将我重定向到 google auth 的路由:

服务器上的 AuthController 类:

export default class AuthenticationController {
  public static async authGoogle(
    req: Express.Request,
    res: Express.Response,
    next: () => void
  ): Promise<void> {
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] })(
      req,
      res,
      next
    );
  }

  public static async authGoogleCallback(
    req: Express.Request,
    res: Express.Response
  ): Promise<void> {
    passport.authenticate('google', {}, (err, user: User) => {
      res.setHeader('Content-Type', 'application/json');

      if (err) {
        logger.error('Login failed', err, JSON.stringify(user));
        res.status(500);
        res.send({
          message: 'Login failed',
          success: false
        });
      } else {
        logger.debug(`User ${user.id} logged in`);
        res.status(200);
        res.cookie('jwt', 1);
        res.send({
          message: 'User logged in',
          success: true,
          token: `${jsonwebtoken.sign(
            JSON.stringify(user),
            process.env.JWT_SECRET || 'DONT_USE_IN_PROD'
          )}`
        });
        res.redirect('/');
      }
      res.end();
    })(req, res);
  }

这是服务器上的身份验证路由器:

export function authenticationRouter(): Router {
  const router = Router();

export function addGoogleRoutes(router: Router): Router {
  // Google auth routes
  router.get('/google', AuthenticationController.authGoogle);
  router.get('/google/callback', AuthenticationController.authGoogleCallback);

  return router;
}

主要问题是,我不明白如何(addGoogleRoutes)从登录组件访问服务器、如何发送请求以及在服务器上执行路由谷歌路由。

这是 next.js 中客户端上的登录组件/页面:

class Login extends React.Component {
  static async getInitialProps() {
    return {};
  }

  handleClick = () => {
    console.log('handle click');
    fetch.post('point google auth route on server');
  };

  render() {
    return (
      <LoginLayout title="Login Page">
        <button className="login-field" onClick={this.handleClick}>
          Login with Google
        </button>
      </LoginLayout>
    );
  }
}

export default Login;

欢迎任何建议或帮助!

标签: javascriptreactjstypescriptexpressnext.js

解决方案


推荐阅读