如何使用Node.js从req.body发送数据

时间:2019-05-11 11:00:29

标签: node.js

如何使用nodejs从身体发送数据?

我正在node.js中编写一个代码,用户可以在其中输入正文中的数据。然后,基于该输入,程序将从数据库中获取数据并以JSON格式显示。

我写了以下代码:

 app.post('/city', (req,res) => {

    var id = parseInt(req.body.id);
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

我觉得var id = parseInt(req.body.id);有问题。因为,当我运行代码时,它说它无法识别ID?

此外,当我在Postman中运行此命令时,出现以下错误:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>TypeError: Cannot read property &#39;id&#39; of undefined
            <br> &nbsp; &nbsp;at app.post (F:\DatabaseProject15\routes\common.js:36:32)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13)
            <br> &nbsp; &nbsp;at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22
            <br> &nbsp; &nbsp;at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12)
            <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10)
            <br> &nbsp; &nbsp;at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
        </pre>
    </body>
</html>

详细信息:

var id = parseInt(req.body.id);

位于F:\DatabaseProject15\routes\common.js:36:32

控制台错误:

TypeError: Cannot read property 'id' of undefined
    at app.post (F:\DatabaseProject15\routes\common.js:36:32)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
    at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12)
    at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10)
    at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)

代码:

  

app.js

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

var common = require('./routes/common')
app.use('/common', common)


app.listen(4600, function () {
    console.log('Server is running.. on Port 8000');
});
  

router / common.js

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


const config = {
    user: 'postgres',
    database: 'mydb',
    host: '40.83.121.72',
    password: 'abc',
    port: 5432
};

const pool = new pg.Pool(config);


app.post('/', (req, res, next) => {
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query('SELECT * FROM city', function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }

             res.status(200).send(result.rows);
        })
    })
 });

 app.post('/city', (req,res) => {
    //var id = parseInt(req.params.id);
    var id = parseInt(req.body.id);
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

app.post('/app/state/:id', (req,res) => {

    var id = parseInt(req.params.id);

    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM state WHERE id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

module.exports = app

1 个答案:

答案 0 :(得分:1)

在路线上方的app.js中添加

app.use(express.json());

这将允许您解析application / json,如果您需要解析application / x-www-form-urlencoded,则需要添加

app.use(express.urlencoded({ extended: true }));