HTTP Module to Request Module Translation

时间:2019-04-23 15:12:17

标签: node.js api

How to rewrite this node.js code, just using the request module not http module?

var options = {
    url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
    }
};
var req = http.request(options, function(res) {
    console.log('Status:' + res.statusCode);
    console.log('Headers: ' + JSON.stringify(res.headers));
    res.on('data', function(body) {
        console.log('Body:' + body);
    });
});

req.write('{"x-api-key":"12345", "Content-Type":"application/json", "appId":"DEMO1","momentId":"GAME_COMPLETE","deviceType":'
    Android ','
    campaignId ':"DEMOCAMP1","rewardGroupId":"amz1yprime"}');
req.end();

I've done part of it:

const request = require('request');
const data = JSON.stringify({
  "appId": "DEMO1",
  "momentId": "GAME_COMPLETE",
  "deviceType": 'Android ',
  'campaignId ': "DEMOCAMP1",
  "rewardGroupId": "amz1yprime"
}) 
const options = {  
    url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetReward',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
  }, 
};

request.post(options, function(err, res, body) {  
    console.log(body);
});

But i don't know how to send "data" and how to get a response to the request

1 个答案:

答案 0 :(得分:0)

重写并不激烈。这是一些简单的更改。

const request = require('request')

var options = {
  url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
  },
  body: {
    'appId': 'DEMO1',
    'momentId':'GAME_COMPLETE',
    'deviceType' : 'Android',
    'campaignId' : 'DEMOCAMP1',
    'rewardGroupId': 'amz1yprime'
  },
  json: true // sets body to JSON representation of value 
};

request.post(options, (err, httpResponse, body) => {
  if (err) console.error(err);
  // httpResponse contains the full response object, httpResponse.statusCode etc
  else console.log(body);
})