Node.js 请求上捕获的错误类型(';';错误)
我正在使用node.js编写一个小代码Node.js 请求上捕获的错误类型(';';错误),node.js,Node.js,我正在使用node.js编写一个小代码 var http = require('http'); var options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console
var http = require('http');
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
我必须为启动发送post请求,我正在发出get请求,这就是为什么没有http.get()。在这个请求中,我得到了404响应代码,这也是一个错误。但在req.on('error')中没有捕获。我想知道这种方法捕获了哪种错误???:
如果在请求过程中遇到任何错误(可能是DNS解析错误、TCP级别错误或实际HTTP解析错误),将在返回的请求对象上发出“错误”事件
因此,该事件可能仅在协议/连接级别出现错误时才会发出
然后,您可以在connect
调用中处理HTTP错误:
var req = http.request(options, function(res) {
if (res.statusCode == "404"){ ... }
else if (...) {
...
} else { // everything ok
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
...
}
});