【发布时间】: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