【发布时间】:2018-11-09 00:01:09
【问题描述】:
我在 ExpressJS 上运行了这个简单的 MySQL 数据库 API。
const express = require('express');
const router = express.Router();
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'andri',
password: '12345',
database: 'andri'
});
app.get('/employees', function (req, res) {
console.log(req);
connection.query('select * from users', function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
app.get('/employees/:id', function (req, res) {
connection.query('select * from users where id=?', [req.params.id], function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
app.post('/employees', function (req, res) {
var postData = req.body;
connection.query("INSERT INTO users (`id`, `userid`, `fullname`, `usergroup`, `emailid`, `mobile`, `title`, `created_at`) VALUES (NULL, '?', '?', '?', '?', '?', '?', CURRENT_TIMESTAMP);",
postData, function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
我可以使用 POSTMAN 测试 GET 函数(员工/和员工/:id)端点工作正常。但是POST功能
{
"userid": "PROJ-12345",
"fullname": "Eko Andri S",
"usergroup": "IT",
"emailid": "eko.andri@xxx.or.id",
"mobile": "0811111111",
"title": "Intern",
"created_at": "2018-05-30T01:59:17.000Z"
}
在 POTSMAN 上得到这个结果:
{
"fieldCount": 0,
"affectedRows": 1,
"insertId": 8,
"serverStatus": 2,
"warningCount": 0,
"message": "",
"protocol41": true,
"changedRows": 0
}
以上记录成功记录在数据库中,但每个字段的值为“?”没有报价;除了正确记录的时间戳。
如果我删除 ?在 INSERT 行中,我收到以下错误
您的 SQL 语法有错误
【问题讨论】:
-
感谢您的帮助,但我尝试了许多组合,它说“您的 SQL 语法有错误”。此语法不起作用“INSERT INTO users, [postData.id, postData.userid,etc] VALUES [NULL,'?','?',...]。你能更具体我应该在? 标记。谢谢
-
查看库中的示例,(它们不会在 ? 周围添加引号,并且它们还将数组作为第二个参数而不是对象传递,也就是说,我想说的是)
-
好的,谢谢,我会调查的。
标签: mysql node.js rest express