简体   繁体   中英

Node.js Update information in mysql

I am trying to implement a function that will update information in the database in MySQL. I cannot find a way to solve this problem. whereby postman is not reading my id, username, email. I manage to make the login and registration to work in my react.js website. but now I want to allow users to able to edit their profile information.

customer.model.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 });
      }
    );
  };

auth-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);
};



在此处输入图片说明

hi @lee soon fatt can you share a screenshot of postman how you passing the data.

the solution: you have to pass id para in URL or you have to store in session

here I am sharing the solution article link

the router allows passing the id para

app.get('/', getHomePage);
app.get('/add', addPlayerPage);
**app.get('/edit/:id', editPlayerPage);
app.get('/delete/:id', deletePlayer);**
app.post('/add', addPlayer);
app.post('/edit/:id', editPlayer);

URL looks like http://localhost:5000/your-route-path/1

id para (Int value) based on the user id you have to pass the end of the URL

I hope you get the links

https://dev.to/achowba/build-a-simple-app-using-node-js-and-mysql-19me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM