【问题标题】:nodeJS - make HTTPS request, sending JSON datanodeJS - 发出 HTTPS 请求,发送 JSON 数据
【发布时间】:2017-02-10 22:49:41
【问题描述】:

我想从一个 nodeJS 服务器发送一个 HTTPS POST 到另一个。我有一些 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.
 */
});

【问题讨论】:

    标签: json node.js https


    【解决方案1】:

    您可以使用原生 https 节点模块通过 POST http 请求发送 JSON 数据,如 stated in the documentation

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

    您应该将 postData 编辑为所需的 JSON 对象

    【讨论】:

    • 这个不行,服务器收不到postData。
    • 我已经尝试过了,它确实有效,请记住,在您将处理请求的服务器中,如果它是节点服务器,数据将包含在 req.body
    • 你拯救了我的一天。我忘了包括req.write(postData);。啊哈时刻
    【解决方案2】:

    我相信以下是您想要的。使用request 库。我的建议见代码中的 cmets。

    ...
    
    var options = {
      hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
      port: 443,
      path: '/',
      method: 'POST',
      json: true
    };
    
    ...
    
    //making a post request and sending up your query is better then putting it in the query string
    app.post('/makeRequest', function(req, res) {
      var query = req.body['query'];
    
      //NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request. 
      //(you may need to make changes on your other servers)
      options.body = { payload: query };
      request(options, function(err, response, body) {
        if (err) {
          //Handle error
          return;
        }
    
        if (response.statusCode == 200) {
          console.log('contents received');
        }
    
      });
    });
    

    【讨论】:

      【解决方案3】:

      正如马特所说,您需要使用request

      发送 JSON 对象而不是 JSON.Stringify 以便在服务器上您可以使用以下方式接收它:

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

      使用以下代码:

      var request = require("request");
      
      request({
              'url':"http://www.url.com",
               method: "POST",
              json: true, 
              body: {'param1':'any value'}
          }, function (error, resp, body) {
              console.log ("check response.");
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-27
        • 2013-09-14
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 2011-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多