在看NodeJS开发指南这本书时,书中的一个例子,讲解http.request的.代码如下:

 var http = require('http');
var querystring = require('querystring');
var contents = querystring.stringify({
name: 'byvoid',
email: '[email protected]',
address: 'Zijing 2#, Tsinghua University',
});
var options = {
host: 'www.byvoid.com',
path: '/application/node/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length' : contents.length
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data);
});
});
req.write(contents);
req.end();

在运行时会出现以下的error:

events.js:72
    throw er;// Unhandled 'error' event
          ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete](dns.js:124:16)

随后,查看了官方关于http.request的函数说明.

将代码host: 'www.byvoid.com',修改为 hostname:url.parse( 'www.byvoid.com').hostname.

即可成功运行.

04-25 07:52