node.js - 使用 bcryptjs 散列 MySql 数据时出错
问题描述
我希望在 expressjs 文件中使用 npm bcryptjs 对我的密码进行哈希处理。在 用户表中,我存储了我的电子邮件和密码。我尝试创建app.post函数来散列密码,如果发现任何错误,则控制台记录它。当我在邮递员中点击 API 时,控制台日志错误显示“ db is not a function ”。我不明白为什么它会显示!请帮我解决这个问题。只是为了通知,我正在使用 Sequelize ORM。
这是我的 server.js 代码
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const bcrypt = require('bcryptjs');
//Express builds REST APIs
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
//cors provides Express middleware for allowing CORS with different options
app.use(cors(corsOptions));
// body-parser parses the request for creating req.body object
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const db = require("./models");
db.sequelize.sync();
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Task Application." });
});
const router = require("./routes/users.routes");
app.use('/api/tutorials', router);
const router1 = require("./routes/task.routes");
app.use('/api/tasks', router1);
app.post('/login', (req, res) => {
res.json('login')
})
app.post('/register', async (req, res) => {
try {
const { email, password } = req.body;
const hash = await bcrypt.hash(password, 8);
await db('users').insert({ email: email, hash: hash });
res.status(200).json('good')
}
catch (e) {
console.log(e);
res.status(500).send('something broke')
}
})
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
解决方案
尝试替换db('users').insert({ email: email, hash: hash })
为db.sequelize.models.users.insert({ email: email, hash: hash })
. 还要交叉检查模型名称是否users
在User
文件中./models
。
欲了解更多信息:https ://sequelize.org/master/manual/model-basics.html
推荐阅读
- excel - 查找并选择在组合框列表中找到的项目
- arrays - Observable 如何获取 Array 的数据?角 6
- postgresql - 从 Debian Docker 容器连接到 Windows Postgres
- javascript - 在 Javascript 中查找对象列表
- javascript - 如何打印属性名称而不是整个 JS 对象?
- c++ - 如何将 A 到 Z 作为变量
- pip - 人工延迟
- bash - 这两个 bash 片段是否等效,如果不是,哪个更好?
- .net - 将引用的组件(类型、方法等)从它们的程序集中提取到目标程序集中
- android - Gradle 同步失败:java.lang.StackOverflowError