[英]make a post request with in node.js application
我有一個帶有/ api / authenticate端點的node.js服務。 我可以使用“用戶名”和“密碼”作為輸入(正文參數)從POSTMAN成功調用此服務。 如何從另一個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' }
以下是另一個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
我想念什么? 任何幫助表示贊賞。
您是否正在嘗試從表單/等獲取已發布的數據?
嘗試使用快遞。
npm install express -save
您可以使用ff從網址獲取發布的數據:
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];
}
}
});
使用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();
但是除非絕對不能使用,否則請使用庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.