2017-09-05 71 views
0

我想使用HTTPClient爲NodeJS發送2個參數的POST請求。在POST請求上空的參數

var HTTPClient = require('httpclient') 

var options = { 
    hostname: 'localhost', 
    path: '/', 
    port: 8081, 
    secure: false, 
    method: 'POST', 
    headers: { 
     'x-powered-by': 'HTTPClient.js' 
    }, 
    'Content-Type': 'application/x-www-form-urlencoded', 
    params:{ 
     command:'TEST', 
     param1:'TEST' 
    } 
} 

var example1 = new HTTPClient(options) 
example1.post('/executeGraph1', function (err, res, body) { 
    console.log(typeof body,body); 
}) 

然後我用快遞趕上POST請求

var express = require('express'); 
var app = express(); 
var path = require('path'); 
var bodyParser = require('body-parser'); 

// configure the app to use bodyParser() 
app.use(bodyParser.urlencoded({ 
    extended: true 
})); 
app.use(bodyParser.json()); 
app.use(express.static(path.join(__dirname, ''))); 

app.post('/executeGraph1', function (req, res) { 
    console.log("Got a POST request for grahBar"); 

    console.log("params",req.params); 
    console.log("body",req.body); 
    console.log("query",req.query); 
}) 

var server = app.listen(8081, function() { 

    var host = server.address().address 
    var port = server.address().port 

    console.log("Example app listening at http://%s:%s", host, port) 
}) 

我曾嘗試在其他問題解決方案,如使用'Content-Type': 'application/x-www-form-urlencoded'或者app.use(bodyParser.urlencoded({extended: true}));,但evrery時間我不斷收到空變量。我曾嘗試尋找屬性身體,參數或查詢,但所有三個選項都是空陣列

有沒有人知道這裏出了什麼問題?

+0

改變你的Content-Type的內容類型'application/x-www-form-urlencoded'到 - >'Content-Type':'application/json' – swapnesh

+0

@swapnesh I已經試過,但結果是一樣的:( –

回答

2

您的服務器的代碼是好的,req.query將包含查詢參數,但req.params當你的路由字符串就是這樣/executeGraph1/:paramName定義使用有可能會更PARAMS與:爲e.g /res1/:param1/res2/:param2/:param3前綴。

Altough我還沒有被使用HttpClient的模塊,添加在請求URL作品查詢字符串,e.g

example1.post('/executeGraph1?queryParamName=value', function (err, res, body) { 
    console.log(typeof body,body); 
    }) 

在你的選擇變量也行更換paramsquery

我建議使用https://github.com/request/request來代替。

POST處理程序中的最後一件東西添加爲最後一行res.end()如果您不這樣做您的請求將掛起並等待超時。 end可能會將參數發送給客戶端。