javascript - 服务器和客户端如何通信?
问题描述
如何从客户端向服务器发送请求,客户端是 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;
欢迎任何建议或帮助!
解决方案
推荐阅读
- python - 建模中的字符串变量
- postgresql - TimescaleDB 连续聚合和 Postgis
- vue.js - Navbar Toggler Bootstrap with VueJS - 在点击外部指令时关闭
- xml - XML 模式设计:在不违反唯一粒子属性的情况下选择相似序列?
- type-conversion - conv_integer() 与 to_integer()
- python - 不知道如何修复我的洗牌和交易的错误 python 程序 IndexError: list index out of range cant figgur
- c++ - 纹理不会出现 FreeGLUT
- node.js - NodeJs / Mongo:在模型中添加新文件
- rust - include_bytes 的运行时成本是多少!或include_str?
- r - 如何使用 R 获取括号/括号中的数字