【问题标题】:How to store user data with node/Express如何使用 node/Express 存储用户数据
【发布时间】:2016-06-10 17:44:23
【问题描述】:

我正在开发我的第一个 Node/Express 应用程序,并且能够创建 具有用户身份验证功能的应用程序。 但我不明白的是,如何将用户连接到他/她在登录后所做的内容(例如设置)以及如何/在哪里保存?
因此,如果另一个用户登录,他/她会使用他们所做的设置获得他们选择的设备。

我的应用程序的目标是控制覆盆子上的传感器,例如打开和关闭它们或从连接的网络摄像头拍照。 那么有人可以解释如何处理来自用户的数据/设置等吗?

如果这是一个愚蠢的问题,我很抱歉。但我是新人,想了解我在做什么,之前我只做过 HTML (S)CSS 和简单的 JS,我不必担心后端部分。

【问题讨论】:

  • 如果我的回复解决了您的问题,请不要忘记接受它。

标签: node.js express


【解决方案1】:

对于身份验证,最好使用 Web 令牌。

https://github.com/auth0/express-jwt

参考:

Node js, JWT token and logic behind

我认为这是一个用于身份验证的 npm 模块。您可以在 github repo 中获得更好的文档。

实现示例链接:

https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

【讨论】:

    【解决方案2】:

    对于在 RPi 或 BONE 上运行的一些 Node 应用程序,我使用了 MongoDB 和 Mongoose ODM。

    更多资源可以在herehere找到

    然后您应该创建一个用户实体/模型并使用标识符存储您的用户。

    示例:

    用户架构.js

    module.exports = {
    user: {
    userId: Number,
    name: String,
    otherSettings: String
    }
    }
    

    schema-builder.js

    var userSchema = require('./user-schema');
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    module.exports = {
        userSchema: new Schema(userSchema.user)
    }
    

    user-repo.js

    var schemaBuilder = require('./schema-builder');
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/mydb');
    
    var User = mongoose.model('User', schemaBuilder.userSchema);
    
    module.exports = {
    getUserById: function(id, callback){
    User.findById(id, callback);
    },
    addNewUser: function(userJson, callback){
    console.log('Adding new user');
    var newUser = new User(userJson);
    newUser.save();
    }
    };
    

    服务器/app.js

    var userRepo = require('./repositories/user-repo');
    
    // Let's say this logic is to look for an existing user
    var user;
    userRepo.getUserById(userId, function(user){
    
    // If no user found, proceed with registration
    // Else, proceed with auth or login. Then use and/or update user
    //..settings as required
    });
    

    希望这会有所帮助!

    【讨论】:

    • 我将用户信息存储在我的用户数据库中。如何明智地存储数据?
    猜你喜欢
    • 1970-01-01
    • 2018-08-10
    • 2023-03-28
    • 2020-07-13
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多