Node.js mysql의 업데이트 정보
26917 단어 node
고객.모델.js
const sql = require("../config/db.config");
const Customer = function(customer) {
this.email = customer.email;
this.username = customer.username;
this.id = customer.id;
};
Customer.updateById = (customer) => {
sql.query(
"UPDATE users SET username = ?, email = ? WHERE id = ?",
[customer.email, customer.username, customer.id],
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found Customer with the id
result({ kind: "not_found" }, null);
return;
}
console.log("updated customer: ", { id: id, ...customer });
result(null, { id: id, ...customer });
}
);
};
au-controller.js
const db = require("../models");
const config = require("../config/auth.config");
const Customer = require("../models/customer.model.js");
const User = db.user;
const Role = db.role;
const Op = db.Sequelize.Op;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
// Save User to Database
User.create({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
})
.then(user => {
if (req.body.roles) {
Role.findAll({
where: {
name: {
[Op.or]: req.body.roles
}
}
}).then(roles => {
user.setRoles(roles).then(() => {
res.send({ message: "User registered successfully!" });
});
});
} else {
// user role = 1
user.setRoles([1]).then(() => {
res.send({ message: "User registered successfully!" });
});
}
})
.catch(err => {
res.status(500).send({ message: err.message });
});
};
exports.signin = (req, res) => {
User.findOne({
where: {
username: req.body.username
}
})
.then(user => {
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // 24 hours
});
var authorities = [];
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
authorities.push("ROLE_" + roles[i].name.toUpperCase());
}
res.status(200).send({
id: user.id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token
});
});
})
.catch(err => {
res.status(500).send({ message: err.message });
});
};
exports.update = (req, res) => {
// Validate Request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
console.log(req.body);
Customer.updateById(
req.body.customerId,
req.body.username,
req.body.email,
new Customer(req.body),
(err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Customer with id ${req.params.customerId}.`
});
} else {
res.status(500).send({
message: "Error updating Customer with id " + req.params.customerId
});
}
} else res.send(data);
}
);
};
auth.routes.js
const { verifySignUp } = require("../middleware");
const controller = require("../controllers/auth.controller.js");
module.exports = function(app) {
app.use(function(req, res, next) {
res.header(
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8081'),
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'),
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'),
res.setHeader('Access-Control-Allow-Credentials', true),
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
app.put("/api/auth/update", controller.update);
};
Reference
이 문제에 관하여(Node.js mysql의 업데이트 정보), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/stevenleesf/node-js-update-information-in-mysql-4c53텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)