javascript - 发送表单时如何自动登录/注册用户?
问题描述
我有一个由 Node.JS + Express + Socket.IO 运行的网站。我正在使用 MongoDB 作为数据库。
我有一个页面,在这个页面中,当用户单击一个按钮时,我会打开一个带有注册表单的引导模式给用户。用户可以在此模式中选择登录表单。
我在 Socket.IO Server 上有 3 个事件,在 Socket.IO Client 上也有 3 个事件。这些是,
Client Server
-----------------------------------
| |
| User Clicks Button |
|------------------------------->>|
| |
| Server emits 'register' event |
|<<-------------------------------|
| |
| Client catches 'register' |
| and opens register/login form |
| Fills the form and submits |
| Client emits 'submit-register' |
| Event |
|------------------------------->>|
| |
| Server checks the submitted |
|form data and emits 'registered' |
| event if user is successfully |
| registered to database, if not |
| emits 'register-error' event |
|<<-------------------------------|
| |
| User catches 'register-error' |
| or 'registered' events and a |
| user opens it's session automa- |
| tically without page refresh |
|---------------------------------|
我想做底层的沟通。我不想让用户在页面上得到任何刷新,但是如果没有解决这个问题,它可以被刷新但它应该打开会话。
我不知道这样做,谢谢。祝你有美好的一天!
解决方案
我建议做护照本地策略。这将允许您通过服务器(节点 + 快递)设置用户身份验证 - 并且当身份验证完成时(登录或注册) - 将响应发送回您的客户端。
在您的客户端上,如果您使用任何类型的具有基于承诺的 http 请求的 JS 框架,您可以等待响应 - 然后根据您的服务器向客户端提供的响应选择发生的情况。
这是使用节点、护照、vue 和 axios 的从前到后的示例: https ://blog.jscrambler.com/vue-js-authentication-system-with-node-js-backend