首页 > 解决方案 > 使用 json 和本地存储注册用户

问题描述

我正在尝试创建一个用户可以登录和注册的 web 应用程序。我必须在本地存储用户列表,这意味着不允许使用 db,并且我有一个名为“usersDB”的 json 文件。
我考虑过使用追加或推送来创建寄存器,但它似乎不起作用,知道如何添加新用户吗?
我的代码:

let userFile = require ("./users.json");
const express = require("express");


const {v4: uuidv4} = require('uuid');
const port = process.env.PORT || 3005;
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());

app.get("/users",((req, res) => {
    res.status(200).send(userFile);
}))
app.get("/products",((req, res) => {
    res.status(200).send(productFile);
}))

app.post(`/register`, async (req, res, next) => {
    
    if(req.body.username.valueOf()===undefined||req.body.password.valueOf()===undefined ){
        res.err("undefined");
    }
    
    let id = genarateUuid();
    // createUser
    //add to db
    let user = {id:id,username:req.body.username,password:req.body.password,cart:[],purchases:[],login:[],sessions:[],isAdmin: false};
    userFile.append(user); //doesn't seem to work
    res.status(200).json(user);
    }
)

标签: reactjsjsonuser-interface

解决方案


看起来你正在使用节点和快递。您需要使用fs来读取/写入文件(我喜欢与path结合使用fs来构建文件路径)。

写入文件(假设 users.json 包含用户对象数组):

const fs = require('fs');

app.post('/register', async (req, res, next) => {
  // build user variable...

  // read current file contents
  const filePath = path.join(process.cwd(), 'users.json');
  const fileData = fs.readFileSync(filePath);
  const data = JSON.parse(fileData);

  // append the new user
  data.push(user);

  // write the file back to users.json
  fs.writeFileSync(filePath, JSON.stringify(data));

  res.status(200).json(user);
});

要从该文件中读取:

app.get('/users', (req, res) => {

  // read current file contents
  const filePath = path.join(process.cwd(), 'users.json');
  const fileData = fs.readFileSync(filePath);
  const data = JSON.parse(fileData);

  res.status(200).json(data);
});

您还可以进一步重构该代码以避免代码重复。例如,创建一个名为 的函数getUsers

const getUsers = (filePath) => {
  const fileData = fs.readFileSync(filePath);
  const data = JSON.parse(fileData);

  return data;
}

希望这可以帮助你!


推荐阅读