提问者:小点点

mysqldatabase未在Postman中反映post请求


我想使用带有mysql的npm包knex将myback-end文件夹与localhost上的mysql数据库连接起来。

步骤:

  1. 在后端项目文件夹(包含knex和mysql)
  2. 中运行nodemon server.js文件
  3. 在《邮差》中,我喜欢:

打开“邮递员”,选择“Post Requst”,复制URL:localhost:3000/myPath“,复制到正文:

{“电子邮件”:“me@gmail.com”,“密码”:“bananas”,“name”:“test”}

单击“发送”

当我打开数据库时,运行查询:“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:UnhandledPromiseRejection.此错误源于在没有catch块的情况下抛出async函数内部,或拒绝未用.catch()处理的承诺。DeprecationWarning:未处理的PromiseRejection被弃用。”


共1个答案

匿名用户

您需要从Express配置bodyparser中间件。为此,只需进行以下配置:

const express = require('express');
const app = express();

app.use(express.json()); //<-- this is the configuration you need.
//Your db configuration

app.post('/mypath', (req,res) => {
   console.log(req.body) //now your body is defined.
})

如果请求带有'content-type':application/json头,那么激活express.json()将解析请求。

您有rejectionErrorHandler,因为您必须在.then()函数之后捕获错误。这里有一个例子:

exports.createUser = (req, res) => {
    db.get().collection('user').insertOne({ "name": req.body.name, "login": req.body.login, "password": req.body.password }).then((result) => {
        res.set('location', `/users/${result.insertedId}`)
        res.status(201).end()
    }).catch((err) => {
        res.status(500).json({ errors: err.message })
    })
}