使用NodeJ更新数据 [英] Update data with NodeJs

查看:54
本文介绍了使用NodeJ更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node app(使用expressJs)更新数据库中的用户数据,但它在终端中返回此错误:

I am trying to update my user data in database with node app (using expressJs) but it returns this error in terminal:

 sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL WHERE `id` = '1'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "UPDATE `users` SET NULL WHERE `id` = '1'"

代码

index.js

var Users = require('./routes/Users');
app.put('/users/:id/update', Users.update);

Users.js

'use strict';

var response = require('../res');

exports.update = function(req, res) {
    req.getConnection(function(err, connection) {
        connection.query('UPDATE `users` SET ? WHERE `id` = ?',  [req.body, req.params.id], function(err, rows) {
            if (err)
                console.log("%s ", err);

            response.success(rows, res);
        });
    });
};

发送请求

你能告诉我我做错了吗?

Can you tell me what i did wrong?

推荐答案

您可以使用以下代码进行操作:

You can do it with the code below:

exports.update = function(req, res) {
  console.log(req.body);
  console.log(req.params);
  req.getConnection(function(err, connection) {
      connection.query('UPDATE `users` SET ? WHERE ?',  [req.body, req.params], function(err, rows) {
          if (err)
              console.log("%s ", err);

          response.success(rows, res);
      });
  });
};

我一直在尝试上面的代码,并且工作正常.

I've been trying with the code above and it's working fine.

确保您的 req.body 不为空,并且 req.body 中的字段与 users 表中的字段相同

Make sure your req.body is not empty and the field in your req.body it's same with the field in your users table.

如果您的 req.body 未定义或为null,则可以将此中间件添加到快递服务器中:

If your req.body is undefined or null, then you can add this middleware to your express server:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

希望它能为您提供帮助.

I hope it can help you.

这篇关于使用NodeJ更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆