2017-06-19 47 views
0

請求對象上出現了錯誤我在那裏我請求對象使用如何發送回撥時的NodeJS

request.on('error', function (e) { 
      console.log("error while sending request: " + e); 
      }); 

捕捉錯誤的情況,但我對如何將這些錯誤發送到困惑客戶端,我必須顯示錯誤。我只能使用res.send();發送響應對象上的錯誤,任何幫助表示讚賞。我沒有使用快遞。

+0

請問Node.js Web服務器中是否發生「請求對象的catch錯誤」?我查看了https://nodejs.org/api/http.html文檔,但沒有找到請求對象的「錯誤」事件。 – shaochuancs

+0

@shaochuancs搜索http.request(options [,callback])# ,你可以找到它或嘗試搜索.on('error' – NagaRajendra

+0

看來你是使用Node.js作爲HTTP客戶端,而不是服務器。 「發送此錯誤到客戶端」是什麼意思?錯誤在客戶端... – shaochuancs

回答

0

如果你想返回響應對象的錯誤,瀏覽器。你可以使用如下代碼:

const http = require('http'); 

let server = http.createServer(function(req, res) { 
    res.statusCode = 403; 
    res.statusMessage = 'Forbidden'; 
    res.write(JSON.stringify({message: 'something bad happens'})); 
    res.end(); 
}); 

server.listen(3000, function() { console.log("Server Listening on http://localhost:3000/"); });