node.js - 使用 cURL CLI 的 HTTPS POST 到 NodeJS 服务器

标签 node.js ssl curl https

我编写了一个 HTTPS NodeJS 服务器(带有自签名证书),我想在其中接收和处理来自 cURL CLI 的 POST 请求。

我的服务器:

var https = require('https');
var fs = require('fs');
var config = require('./conf.json');
var g3updater_kernel = require('./g3updater_kernel');
var express = require('express');
var app = express();

var privateKey  = fs.readFileSync(config.security_repository+'/CA/rootCA.key', 'utf8');
var certificate = fs.readFileSync(config.security_repository+'/CA/rootCA.pem', 'utf8');

var httpsOptions = {
  key: privateKey,
  cert: certificate
}

app.post('/', function(req, res){
    console.log(req.query);
});


https.createServer(httpsOptions, app).listen(443);

我使用的 cURL 命令:

curl -d M=1 https://localhost/ -k

问题是我收到一个空查询。 console.log(req.query) 显示:

{}

我在查询中遗漏了什么吗?

最佳答案

为了解析您的帖子请求中的查询,您需要使用 body-parser .

在 Express 4 中,有意识地决定将 bodyParser 和 CookieParser 移动到单独的模块中。

为了访问您的查询,您的代码应该类似于:

var https = require('https');
var fs = require('fs');
var config = require('./conf.json');
var g3updater_kernel = require('./g3updater_kernel');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var privateKey  = fs.readFileSync(config.security_repository+'/CA/rootCA.key', 'utf8');
var certificate = fs.readFileSync(config.security_repository+'/CA/rootCA.pem', 'utf8');

var httpsOptions = {
  key: privateKey,
  cert: certificate
}

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.post('/', function(req, res){
    console.log(req.body);
});

https.createServer(httpsOptions, app).listen(443);

请注意,它们将保存在 req.body 而不是 req.query 中。

编码愉快!

关于node.js - 使用 cURL CLI 的 HTTPS POST 到 NodeJS 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072402/

相关文章:

javascript - 要求不按我想象的方式工作

javascript - 使用javascript在IE中导入客户端证书

python - 如何处理 pycurl.error - 超时异常?

node.js - Mongoose:在查询条件中的架构字段上应用函数

javascript - 使用 Node.JS Mongoose 查找文档并将值插入到 MongoDB 中的数组中

node.js - 使用 socket.io 将私有(private)详细信息发送到每个套接字

TCP SSL 中的 PHP stream_socket_client 与 cURL

java - java 代码中的curl POST 不起作用。从 shell 工作正常

php - 使用 curl put 上传文件 - multipart/form-data