【发布时间】:2019-12-26 09:49:38
【问题描述】:
我在使用 Node.JS 和 Postman 向 MYSQL 插入数据时遇到问题
我创建了 3 个文件 - db.js、server_db.js、server.js。 Server.JS 是我们执行 GET/POST 时调用的主文件。我无法在 MYSQL DB 中插入任何记录。我正在遵循 Promise 代码 - 此处拒绝/响应。
-
db.js-
var mysql = require("mysql"); var db_config ={ host : '127.0.0.1', user : 'root', password : '*****', database : 'webapp' }; var connection; console.log("inside db.js 1") connection = mysql.createConnection(db_config); connection.connect(function(err){ if(err) throw err console.log('You are now connected..'); }); module.exports = connection;
server_db.js (此文件包含要触发的 SQL 查询,并在此处使用 Promises 来解析和拒绝)
var db = require('../db.js');
save_user_information = (data) => new Promise((resolve, reject)=>{
db.query('INSERT INTO lottery_information SET ?',data,function(err,results,fiels){
if(err){
reject('could not insert into lottery information');
}
resolve('Successful');
});
});
module_exports = {save_user_information};
服务器.js
我们从哪里调用 API
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const save_user_information = require('./models/server_db');
app.use(bodyParser.json());
app.post('/', async function(req, res){
var email = req.body.email;
var amount = req.body.amount;
if(amount <= 1){
return_info = {};
return_info.error = true;
return_info.message = "The amount should be greater than 1";
return res.send(return_info);
}
var result = await save_user_information({"amount" : amount, "email" : email});
res.send(result);
});
app.listen(3000, ()=>{
console.log('Server is running on port 3000');
});
我收到错误 -
(node:17568) UnhandledPromiseRejectionWarning: TypeError: save_user_information is not a function
at C:\GIT\Web2.0\server.js:41:23
at Layer.handle [as handle_request] (C:\GIT\Web2.0\node_modules\express\lib\router\layer.js:95:5)
at next (C:\GIT\Web2.0\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\GIT\Web2.0\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\GIT\Web2.0\node_modules\express\lib\router\layer.js:95:5)
at C:\GIT\Web2.0\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\GIT\Web2.0\node_modules\express\lib\router\index.js:335:12)
at next (C:\GIT\Web2.0\node_modules\express\lib\router\index.js:275:10)
at C:\GIT\Web2.0\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\GIT\Web2.0\node_modules\raw-body\index.js:224:16)
(node:17568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
因此,“save_user_information”似乎没有被视为功能。
你能告诉我哪里出错了。
【问题讨论】:
标签: javascript mysql node.js express postman