node如何请求服务器?
使用HTTP模块的request方法对服务器进行请求。在HTTP连接中报文分为请求(request)和响应(response)两种。下面我们来看一下node如何请求服务器。

nodejs请求服务器(request):
使用node.js对服务器进行请求http.request
通过Node.js本身的事件驱动性(通过事件监听on()),可以处理请求后返回的数据。
const options = {
hostname: 'localhost',
port: 8080,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
//设置属性内容
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
console.log(`响应头: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
//设置格式
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
//${}模版字符串语法
});
//监听data事件,并且将获得到的数据进行打印
res.on('end', () => {
console.log('响应中已无数据.');
});
//监听end事件,响应结束时弹出提示
});
req.on('error', (e) => {
console.error(`请求遇到问题: ${e.message}`);
});
//监听error事件,响应出错时弹出错误信息通过write函数可以向监听服务器端发送数据
服务端响应
新建一个http服务器并且在8080端口上进行监听。
http.createServer(function (req, response){
// 定义了一个post变量,用于暂存请求体的信息
var post = '';
// 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
req.on('data', function(chunk){
post += chunk;
});
// 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
req.on('end', function(){
post = querystring.parse(post);
console.log(post);
});
//读取文件下的值并且将获得数据写入响应,并结束响应。
fs.readFile('data.txt', function readData(err, data) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(data);
});
}).listen(8080, '127.0.0.1');关于请求方面的问题
1.作为后台与前台的一种数据交流方式,所有的http模块使用的前提就是要有一个后台端口,并且按照后台的要求填写headers方面的信息,如Cookie,host,Referer,Origin。然后option中的host,path,以及protocol是http还是https。
2.传输的数据(req.write)必须是流或者是字符串,所以注意参数的类型