调用POST API前端节点JS

时间:2017-04-16 11:11:40

标签: javascript node.js post node-rest-client

我是nodeJS的初学者。

我想做什么:

我有一个托管的POST API,当我使用postman调用它时,它给出了正确的响应,如下图所示:

enter image description here

但是当我尝试使用NodeJS node-rest-client(https://www.npmjs.com/package/node-rest-client)尝试使用它时,它会给我一个不相关的大对象,如下所示:

IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: true,
     ended: true,
     endEmitted: true,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: false,
  domain: null,
  _events: 
   { end: [ [Function: responseOnEnd], [Function] ],
     data: [Function],
     error: [Function] },
  _eventsCount: 3,
  _maxListeners: undefined,
  socket: 
   Socket {
     connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: null,
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,

我需要帮助才能找到合适的物品而且我无法弄清楚我在这里做错了什么。

以下是我调用REST API的代码:

app.get('/notes', cors(), function(req, res) {

    var args = {
                "hiveMachineIp": "192.168.0.110",
                "hiveMachinePort": "10000",
                "hiveUsername": "nt",
                "hivePassword": "",
                "hiveDatabaseName": "default",
                "hiveTableName": "transactions_24m",
                "hiveAggregationColumn": "customerid",
                "hiveAggregationFunction": "HISTOGRAM",
                "hiveAggregationHistogramBin": "5"
            };

    var Client = require('node-rest-client').Client;

    var client = new Client();

    client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, function (data, response) {
        // parsed response body as js object 
        // console.log(data);
        // raw response 
        console.log(response);
    });

    // registering remote methods 
    client.registerMethod("postMethod", "http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", "POST");

    client.methods.postMethod(args, function (data, response) {
        // parsed response body as js object 
        // console.log(data);
        // raw response 
        console.log(response);
    });

})

2 个答案:

答案 0 :(得分:0)

您可以像这样使用axios

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

答案 1 :(得分:0)

在您的代码中,您执行了两次请求,一次是client.post,然后通过调用之前注册的client.methods.postMethod。你应该做一个或另一个,每个回调中的response变量来自http客户端,它不是你的原始json响应。您的数据已经过解析,并且位于data变量中。

要向其他服务器发送一个帖子请求,您应使用client.post或按client.registerMethod注册您的方法,然后client.methods.registeredMethodName发送请求。

当您需要在代码中多次发送相同的发布请求时,请定义一个处理该请求响应的函数,例如:

function handleResponseA(data, response) {
    if(response.statusCode == 200){
        console.log(data);
    } else {
        switch(response.statusCode){
            case 404:
                console.log("Page not found.");
            break;

            case 500:
                console.log("Internal server error.");
            break;

            default:
                console.log("Response status code: " + response.statusCode);
        }
    }
}

然后是client.post

client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, handleResponseA);
client.post("http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", args, handleResponseA);

并通过注册方法完成它,注册方法:

client.registerMethod("postMethod", "http://163.47.152.170:8090/MachinfinityDataPreparation/machinfinitydataprep/hiveDataAggregation/", "POST");

然后调用已注册的方法:

client.methods.postMethod(args, handleResponseA);
client.methods.postMethod(args, handleResponseA);