简体   繁体   中英

HTTPS POST using cURL CLI to a NodeJS server

I wrote an HTTPS NodeJS server (with a self signed certificate) where I want to receive and process POST requests from cURL CLI.

My server:

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 command I use:

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

The problem is that I receive an empty query. console.log(req.query) displays:

{}

am I missing something in the query?

In order to parse the queries in your post request you're going to want to use body-parser .

In Express 4, there was conscious decision made to move bodyParser and CookieParser to separate modules.

In order to access your queries, you're code should look something like:

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);

Note that they will be held in req.body instead of req.query.

Happy Coding!

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