2015-12-29 90 views
0

我使用/ api/authenticate endpoint創建了一個node.js服務。我可以使用'用戶名'和'密碼'作爲輸入(主體參數)從POSTMAN成功地調用這項服務。如何從另一個node.js服務器調用相同的服務?在node.js應用程序中發出發佈請求

有了郵遞員,我得到,

body: {name: 'xxxxxx', password: 'xxxxxx' } 
headers: { 'content-type': 'application/x-www-form-urlencoded', 
    host: 'xx.xx.xx.xx:xxxx', 
    connection: 'close', 
    'content-length': '0' } 

POST/API /認證200 1.336毫秒 - 72

以下是另一個應用程序的NodeJS ......這使得成功的請求呼叫,但沒有任何身份參數(用戶名和密碼)到達認證服務器api時。

var my_http = require('http'); 

app.get('/makeacall', function(req, res) { 
    var output = ''; 
    var options = { 
    body: { name: 'xxxxxx', password: 'xxxxxx' }, 
    method: 'POST', 
    host: 'xx.xx.xx.xx', 
    port: 'xxxx', 
    path: '/api/authenticate', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
    } 
    }; 

console.log('before request'); 

var req = my_http.request(options, function(response) { 
    console.log('response is: ' + response); 
    console.log('Response status code: ' + response.statusCode); 
    response.on('data', function(chunk) { 
    console.log('Data ..'); 
    output += chunk; 
    }); 
    response.on('end', function(chunk) { 
    console.log('Whole Data ..' + output); 
    }); 

}); 
req.on('error', function(err) { 
    console.log('Error: ' + err); 
}); 
req.end(); 
console.log('444'); 
res.send({ message: 'View record message'}); 

});

從此nodejs應用程序,我得到服務器上的空主體。

body: {} 
headers: { 'content-type': 'application/x-www-form-urlencoded', 
    host: 'xx.xx.xx.xx:xxxx', 
    connection: 'close', 
    'content-length': '0' } 
POST /api/authenticate 200 1.336 ms - 72 

我在想什麼?任何幫助表示讚賞。

回答

1

使用的的NodeJS股票HTTP庫不允許使用這種語法。

看看RequestJS作爲一個更簡單的解決方案。它會讓你的生活變得輕鬆許多,並允許你使用你想要的語法。

這是使用庫存節點完成它的解決方案。

https://nodejs.org/api/http.html#http_http_request_options_callback

相關配件:

var postData = querystring.stringify({ 
    'msg' : 'Hello World!' 
}); 

,然後在結尾:

// write data to request body 
req.write(postData); 
req.end(); 

但使用庫,除非你絕對不能。

1

你想從表單/ etc獲取發佈的數據嗎?

嘗試使用快遞。

npm install express -save

你可以從與FF的URL發佈的數據:

app.post('*', function(request, response){ 
    var post = {}; 
    if(Object.keys(request.body).length){ 
     for(var key in request.body){ 
      post[key] = request.body[key]; 
      console.log(key+'=>'+post[key]; 
     } 
    } 
}); 
相關問題