简体   繁体   中英

Express: trying to get JSON data from POST request

I have a nodeJS server. I want to be able to take POST request and read the JSON data from within it.

/**
 * Created by daniel on 27/01/17.
 */

    const pug = require('pug');
    var cloudinary = require('cloudinary');
    var express = require('express');
    var multer  = require('multer');
    var upload = multer({ dest: 'uploads/' });
    var request = require('request');
    var https = require('https');
    var fs = require('fs');
    var morgan = require('morgan');
    var bodyParser = require('body-parser');


    var app = express();
    var jsonParser = bodyParser.json();

https.createServer({
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem')
}, app).listen(3000);

cloudinary.config({
        cloud_name: 'INSERT-CLOUD-NAME-HERE',
        api_key: 'INSERT-KEY-HERE',
        api_secret: 'INSERT-SECRET-HERE'
    });



app.get('/', function (req, res) {
    res.header('Content-type', 'text/html');
    return res.end('<h1>Hello, Secure World!</h1>');
});

    app.post('/', jsonParser, function(req, res){
        student_id = req.body['student_id'];
        console.log(req.body['student_id']);

        res.header('Content-type', 'text/html');
        return res.end('<h1>' + student_id + '<h1>');

    });

I am using Postman to send a POST request with key: student_id and value: 123. However, console.log(req.body['student_id']); is printing undefined. Printing req.body just returns {}. What's up?

Best way is to use the body-parser middleware to parse the incoming object. Here is an example:

var bodyParser = require('body-parser');
var app = require('express')();

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

//Now you can just access the json in the body of the request
app.post('/', function(req, res) {
  res.send(req.body);
}

app.listen(3000);

I'm sure you will be able to incorporate this in your own solution.

My issue was with Postman. I was not correctly sending JSON data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM