我想在這裏按照文檔我如何用Node.js的HTTP客戶端發表文章?
http://nodejs.org/api/http.html
但我不能找到做一些簡單的,如張貼到URL的用戶名和密碼的文檔。我將如何做到這一點?
我想在這裏按照文檔我如何用Node.js的HTTP客戶端發表文章?
http://nodejs.org/api/http.html
但我不能找到做一些簡單的,如張貼到URL的用戶名和密碼的文檔。我將如何做到這一點?
如果你需要做的不僅僅是一個POST更多的事情,比如消費一個RESTful API,我建議你看一看restler。
它有一個非常簡單的API
var rest = require('restler');
rest.post('http://service.com/login', {
data: { username: 'foo', password: 'bar' },
}).on('complete', function(data, response) {
if (response.statusCode == 200) {
// you can get at the raw response like this...
}
});
Node.js的文檔不會在這個
http://nodejs.org/api/http.html#http_http_request_options_callback
這是我會怎麼做請求,使用查詢字符串來特別清楚解析輸入。
//require a few things.
var http = require('http'),
qs = require('qs');
//These are the post options
var options = {
hostname: 'www.mysite.com',
port: 80,
path: '/auth',
method: 'POST'
};
//The postdata can be anything, but I'm using querystring
//to convert it into the format
//username=User&password=Password to be easily parsed in php
var postdata = qs.stringify({
username:"User",
password:"Password"
});
//Initialise the variable that will store the response
var body='';
//Now we're going to set up the request and the callbacks to handle the data
var request = http.request(options, function(response) {
//When we receive data, we want to store it in a string
response.on('data', function (chunk) {
body += chunk;
});
//On end of the request, run what we need to
response.on('end',function() {
//Do Something with the data
console.log(body);
});
});
//Now we need to set up the request itself.
//This is a simple sample error function
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
//Write our post data to the request
request.write(postdata);
//End the request.
request.end();
或者也許看看superagent => https://github.com/visionmedia/superagent – Alfred