nodeJS - 发出HTTPS请求,发送JSON数据

时间:2017-02-10 22:49:42

标签: json node.js https

我想从一个nodeJS服务器向另一个nodeJS服务器发送HTTPS POST。我有一些JSON数据我希望通过此请求发送(由html表单填充)。

我该怎么做?我知道https.request()但似乎没有选择将JSON包含在查询中。根据我的研究,似乎可以使用HTTP请求,但不是HTTPS请求。我该如何解决这个问题?

#import "JVFloatLabeledTextField.h"

typedef enum {
  SBIconLocationHomeScreen = 0,
  SBIconLocationDock       = 1,
  SBIconLocationSwithcer   = 2
} SBIconLocation;

@interface SBApplicationIcon
- (void)launchFromLocation:(SBIconLocation)location context:(id)arg2;
@end

%hook SBApplicationIcon

- (void)launchFromLocation:(SBIconLocation)location context:(id)arg2 {

  UIWindow *window = [[UIApplication sharedApplication] keyWindow];

  UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  [blurEffectView setFrame:window.bounds];
  [UIView transitionWithView:window duration:0.4 options:UIViewAnimationOptionTransitionCrossDissolve animations: ^ {
      [window addSubview:blurEffectView];
  } completion:nil];
  blurEffectView.translatesAutoresizingMaskIntoConstraints = NO;
  [window addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[blurEffectView]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(blurEffectView)]];
  [window addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[blurEffectView]|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(blurEffectView)]];

  JVFloatLabeledTextField *pwt = [[%c(JVFloatLabeledTextField) alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
  pwt.font = [UIFont systemFontOfSize:16.0f];
  pwt.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Enter your password", @"")
                                                                     attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
  pwt.textColor = [UIColor whiteColor];

  pwt.floatingLabelFont = [UIFont boldSystemFontOfSize:11.0f];
  pwt.floatingLabelTextColor = [UIColor greenColor];
  pwt.tintColor = [UIColor greenColor];
  pwt.keyboardType = UIKeyboardTypeNumberPad;
  pwt.translatesAutoresizingMaskIntoConstraints = NO;
  pwt.clearButtonMode = UITextFieldViewModeWhileEditing;
  [UIView transitionWithView:window duration:0.4 options:UIViewAnimationOptionTransitionCrossDissolve animations: ^ {
      [window addSubview:pwt];
  } completion:nil];
  [window addConstraints:[NSLayoutConstraint
                             constraintsWithVisualFormat:@"V:|-210-[pwt(>=44)]"
                             options:NSLayoutFormatDirectionLeadingToTrailing
                             metrics:nil
                             views:NSDictionaryOfVariableBindings(pwt)]];
  [window addConstraints:[NSLayoutConstraint
                             constraintsWithVisualFormat:@"H:[pwt]"
                             options:0
                             metrics:nil
                             views:NSDictionaryOfVariableBindings(pwt)]];
  [window addConstraint:[NSLayoutConstraint
                            constraintWithItem:pwt attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:window attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

}

%end

3 个答案:

答案 0 :(得分:3)

您可以通过POST http请求使用本机https节点模块发送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对象

答案 1 :(得分:0)

我相信以下是你想要的。使用request库。请参阅代码中的注释以获取我的建议。

...

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

  });
});

答案 2 :(得分:0)

如马特所说,您需要使用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.");
    });