Node.js mysql의 업데이트 정보

26917 단어 node
MySQL에서 데이터베이스의 정보를 업데이트하는 기능을 구현하려고 합니다. 이 문제를 해결할 방법을 찾을 수 없습니다. 우체부는 내 ID, 사용자 이름, 이메일을 읽지 않습니다. 내 react.js 웹 사이트에서 작동하도록 로그인 및 등록을 관리합니다. 하지만 이제 사용자가 자신의 프로필 정보를 편집할 수 있도록 허용하고 싶습니다.

고객.모델.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);
};





좋은 웹페이지 즐겨찾기