reactjs - 使用 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);
}
)
解决方案
看起来你正在使用节点和快递。您需要使用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;
}
希望这可以帮助你!
推荐阅读
- sql - NULL SQL 查询后需要错误 424 对象
- loops - 将电子邮件发送到第三方平台时,电子邮件不会在 Google Sheet 上循环
- python - 如何优化 SQLite 数据库中的循环和数据存储?
- excel - 分组依据、排序依据和差异
- c++ - 将每个对象独立渲染到空间中,并在 3D 场景上渲染 2D 场景
- c# - 具有 filterString 属性的自动 datagridview 过滤器控件(对话框)
- c# - 使用 c# 更改特定的 wpf 数据网格行颜色
- sql-server - 从 SQL Server 中的 getdate() 中选择特定的小时和分钟
- symfony - API 平台 - 没有主键,通过两个非唯一字段访问
- java - 如何在 JFrame 内的 JPanel 内显示 JPanel?