2016-02-18 44 views
2

我在與Content-type: 'application/x-www-form-urlencoded'如何發佈與內容類型的Node.js數據=「應用/的X WWW的形式,進行了urlencoded」

var loginArgs = { 
    data: 'username="xyzzzzz"&"password="abc12345#"', 

    //data: { 
    // 'username': "xyzzzzz", 
    // 'password': "abc12345#", 
    //}, 

    headers: { 
      'User-Agent': 'MYAPI', 
      'Accept': 'application/json', 
      'Content-Type':'application/x-www-form-urlencoded'  
    } 
}; 

,並張貼在發佈node.js的數據有問題要求是:

client.post("http:/url/rest/login", loginArgs, function(data, response){ 
console.log(loginArgs); 

if (response.statusCode == 200) { 
    console.log('succesfully logged in, session:', data.msg); 
} 

它總是返回用戶名/密碼不正確

在REST API據說請求體應該是:

username='provide user name in url encoded 
format'&password= "provide password in url encoded format' 
+1

[如何在node.js中創建HTTP POST請求?](http://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request -in-節點-JS) –

回答

8

request支持application/x-www-form-urlencodedmultipart/form-data和形式上傳。對於multipart/related請參閱multipart API。

應用程序/ x-WWW窗體-urlencoded(URL編碼形式)

URL編碼形式是簡單的:

const request = require('request'); 

request.post('http:/url/rest/login', { 
    form: { 
    username: 'xyzzzzz', 
    password: 'abc12345#' 
    } 
}) 
// or 
request.post('http:/url/rest/login').form({ 
    username: 'xyzzzzz', 
    password: 'abc12345#' 
}) 
// or 
request.post({ 
    url: 'http:/url/rest/login', 
    form: { 
    username: 'xyzzzzz', 
    password: 'abc12345#' 
    } 
}, function (err, httpResponse, body) { /* ... */ }) 

參見:https://github.com/request/request#forms

或者,使用request-promise

const rp = require('request-promise'); 
rp.post('http:/url/rest/login', { 
    form: { 
    username: 'xyzzzzz', 
    password: 'abc12345#' 
    } 
}).then(...); 

參見:https://github.com/request/request-promise#api-in-detail

相關問題