【发布时间】:2017-01-31 02:41:06
【问题描述】:
我有一个 nodeJS 服务器。我希望能够接受 POST 请求并从中读取 JSON 数据。
/**
* 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>');
});
我正在使用 Postman 发送一个带有 key: student_id 和 value: 123 的 POST 请求。但是,console.log(req.body['student_id']); 正在打印未定义。
打印 req.body 只返回 {}。怎么了?
【问题讨论】:
-
正如标题所暗示的那样,您不会从该 POST 请求中收到任何 JSON。
-
你能解释一下吗?您的意思是 POST 请求不包含 JSON 或者我不会收到任何内容?如何接收 JSON?