【发布时间】:2020-11-17 07:30:26
【问题描述】:
我想使用 npm 包 knex 和 mysql 将 myback-end 文件夹与 localhost 上的 mysql 数据库连接。
步骤:
- 在后端项目文件夹(包含 knex 和 mysql)中运行 nodemon server.js 文件
- 在 Postman 中,我这样做:
打开Postman,选择Post Requst,复制URL:localhost:3000/mypath,复制到body:
{ “电子邮件”:“me@gmail.com”, "密码":"香蕉", “名称”:“测试” }
-
点击发送
-
当我打开数据库时,运行查询:“SELECT * FROM users;” - 我没有看到任何数据。
你知道会发生什么吗?
这是 server.js 文件中的代码:
const express = require('express');
const db = require('knex') ({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'mydatabase'
}
});
const app = express();
app.use(express.json());
const database = {
users: [
{
id: '123',
name: 'John',
email: 'john@gmail.com',
password: 'cookies'
},
{
id: '124',
name: 'Sally',
email: 'sally@gmail.com',
password: 'cake',
}
]
}
app.get('/',(req,res) => {
res.send(database.users);
})
app.post('/mypath', (req,res) => {
const {email, name, password} = req.body;
db('users').insert({
name: name,
email: email,
password: password
}).then (console.log(req.body))
res.json(database.users);
})
app.listen(3000, () => {
console.log('app is running on port 3000');
})
由于某种原因,我收到错误消息:“node:13376 UnhandledPromiseRejectionWarning: Unhandled PromiseRejectionWarning: Unhandled Promise RejectionWarning: Unhandled Promise Rejection Warning: Unhandled PromiseRejectionWarning: Unhandled Promise Rejection: Unhandled Promise RejectionWarning: Unhandled Promise RejectionWarning: Unhandled PromiseRejectionWarning: Unhandled PromiseRejectionWarning:
由于某种原因,我收到错误消息。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch( ). DeprecationWarning:不推荐使用未处理的 Promise 拒绝。”
【问题讨论】:
-
您能否显示您请求的
req.body?你能完整的表达你的快递应用文件吗? -
请求正文在 Postman 中:{ "email":"me@gmail.com", "password":"Bananas", "name":"Test" } - 我没有快速应用文件中的请求正文。我想使用 Postman 将 json 数据发布到数据库。由于某种原因,没有数据发布到数据库中。