Dan*_*Bak 2 https json node.js
我想将 HTTPS POST 从一个 nodeJS 服务器发送到另一个。我有一些 JSON 数据要随此请求发送(由 html 表单填充)。
我怎样才能做到这一点?我知道 https.request() 但似乎没有将 JSON 作为查询的一部分包含在内的选项。根据我的研究,HTTP 请求似乎可以,但 HTTPS 请求不行。我该如何解决这个问题?
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 bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
Run Code Online (Sandbox Code Playgroud)
您可以使用本机 https 节点模块通过 POST http 请求发送 JSON 数据,如文档中所述
http.request() 中的所有选项都是有效的。
因此,以 http.request() 为例,您可以执行以下操作:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
Run Code Online (Sandbox Code Playgroud)
您应该编辑postData到您想要的 JSON 对象