【问题标题】:Error in inserting DB record using Node.JS and MySQL使用 Node.JS 和 MySQL 插入数据库记录时出错
【发布时间】:2020-12-26 04:41:55
【问题描述】:

我正在使用 MySQL 和 NodeJS express 为 RESTFUL API 执行 CRUD 操作。将记录插入数据库时​​出错,我不知道为什么会出现问题,因为我从 SQL 中复制了插入查询,它工作正常。我写了一个这样的查询var sql = 'INSERT INTO tblltest values(null, "+req.body.Name+")';。我已经使用 PostMan 对其进行了测试,而不是添加名称,它将 +req.body.Name+ 参数添加到数据库中。请帮我解决这个问题。

这是我的代码行:

var express = require('express');
var mysql = require('mysql');
var app = express();
const bodyparser = require('body-parser');

var connection = mysql.createConnection({
    
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'sampledb'
    
});
app.post('/' , function(req , resp) {
    var bg = req.body;
    
    var sql = 'INSERT INTO `tblltest` values(null, "+req.body.Name+")';

    connection.query(sql , function(error , rows , fields){
        if(!error){
            
            console.log('Successful added!! \n');
            resp.json(rows);
            
        }else{
            console.log('Error in adding');
        }
        
    });
})

app.listen(1337);

【问题讨论】:

  • 您的查询字符串错误。请使用'INSERT INTO "tblltest" values(null, "'+req.body.Name+'")';
  • @NarendraKumawat 先生,它不起作用。 “TypeError:无法读取未定义的属性“名称”
  • 这在我看来问题太多了。请edit your question 并包含代码的 html 部分。如果req.body.something 没有从您的html 具有发布操作的字段中获取值,您通常会得到undefined 值。所以,首先我想看看你是如何从对应的 html 中获得 req.body.Name 的。还有var bg = req.body; 是做什么的?

标签: mysql node.js express xampp body-parser


【解决方案1】:

我认为您的 sql 变量中缺少单引号,而不是

var sql = 'INSERT INTO `tblltest` values(null, "+req.body.Name+")';

替换为:

var sql = 'INSERT INTO `tblltest` values(null, "' + req.body.Name + '")';

编辑: 从您的应用程序配置的外观来看,您的应用程序似乎没有使用 bodyParser,请尝试将其添加到您的应用程序(在 app.post(...) 之前),以便它能够使用 body parser 从 POST 获取信息和/或 URL 参数:

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

另外,使用console.log查看你的body对象中是否有数据,尝试在你的sql查询之前添加:

console.log(req.body);

【讨论】:

  • 先生,它不工作。 “TypeError:无法读取未定义的属性“名称”
  • @UsamaHafeez 请检查我编辑的答案。
  • 现在我按照您的要求进行编码,但邮递员仍然出错。如果在 URL (localhost:1337/Usama) 中传递名称,则会出现问题,它会给出错误无法 POST/Usama。但是如果 URL(localhost:1337) 像这样在数据库中保存空字符串。 app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json()); app.post('/' , function(req , resp) { console.log(req.body); var sql = 'INSERT INTO tblltest values(null, "' + req.params.Name + '" )';` connection.query( sql , function(error , rows , fields){ })`
  • 这很奇怪,如果你要发送这样的帖子imgur.com/B9zuLaS,req.body 应该有 name 参数。如果您使用的是 express v4.16.0 或更高版本,我的想法已经不多了。您可以尝试这个答案stackoverflow.com/questions/4295782/… 抱歉,我希望能够提供帮助。
猜你喜欢
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多