首页 > 解决方案 > 使用 bcryptjs 散列 MySql 数据时出错

问题描述

我希望在 expressjs 文件中使用 npm bcryptjs 对我的密码进行哈希处理。在 用户表中,我存储了我的电子邮件和密码。我尝试创建app.post函数来散列密码,如果发现任何错误,则控制台记录它。当我在邮递员中点击 API 时,控制台日志错误显示“ db is not a function ”。我不明白为什么它会显示!请帮我解决这个问题。只是为了通知,我正在使用 Sequelize ORM。

给定的图像是mysql数据库

这是我的 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}.`);
});

标签: node.jsexpresshashbcrypt

解决方案


尝试替换db('users').insert({ email: email, hash: hash })db.sequelize.models.users.insert({ email: email, hash: hash }). 还要交叉检查模型名称是否usersUser文件中./models

欲了解更多信息:https ://sequelize.org/master/manual/model-basics.html


推荐阅读