简体   繁体   English

处理Node.js中的套接字挂起错误

[英]Handling a socket hang up error in Node.js

Hi I am getting the following error when I try to hit a URL from my node.js. 嗨,当我尝试从我的node.js中访问URL时,出现以下错误。

Problem with request: 请求问题:

socket hang up 套接字挂断

My code is below: 我的代码如下:

var express = require('express')
app = express.createServer();
var options = {
    host:'10.230.125.54',
    port:8080,
    path:'/'
};
var http = require('http');
app.get('/hitmideation', function(req, response) {
    var jsonresponse;
    response.contentType('application/json');
    console.log('listening');
    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);
            jsonresponse = chunk;
            response.end('json from url:'+ JSON.stringify(jsonresponse));
        });
    });
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
    req.end();
});
console.log('I will be listening on: 1340' );
app.listen(1340);

How do I handle this issue? 我该如何处理? Any help will be appreciated 任何帮助将不胜感激

Be sure your url in the options work properly by testing it in a browser. 通过在浏览器中进行测试,确保options的url正常运行。 If you are sure the url is responding try following code snippet to retrieve the content: 如果您确定url响应,请尝试使用以下代码片段检索内容:

http.get("10.230.125.54:8080", function(res) {
    res.setEncoding('utf8');
    var content = '';
    res.on('data', function (chunk) {
        content += chunk;
    });
    res.on('end', function () {
        var obj = JSON.parse(content);
        // do whatever with the obj
    });
}).on('error', function(err) {
       // Handle the err here
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM