Node.js-错误:套接字挂断

时间:2018-06-28 17:52:09

标签: node.js http express

我尝试通过具有代理域的json.placeholder API获取数据。我已使用auth标头通过此代理进行了身份验证。该身份验证标头需要发送给每个请求。但是我得到一个错误:

error: { Error: socket hang up
at createHangUpError (_http_client.js:331:15)
...
at process._tickCallback (internal/process/next_tick.js:180:9) code: 'ECONNRESET' }

我的代码如下:

app.get('/users/1', (req, res) => {
    const options = {
        host: 'velodrome.usefixie.com',
        port: 80,
        path: 'http://jsonplaceholder.typicode.com' + req.path,
        headers: {
            'Content-Type': 'application/json',
             Host: 'jsonplaceholder.typicode.com',
            'Proxy-Authorization': `Basic ${new Buffer(auth).toString('base64')}`,
        }
    };

    const x = http.get(options, (request) => {
        request.on('data', (locations) => {
            buffer = new Buffer(locations);
        });
        request.pipe(res);
    }).on('error', (err) => console.log('error:', err));
    x.end();
});

1 个答案:

答案 0 :(得分:0)

您的options.host应该是您要呼叫的远程主机,例如http://jsonplaceholder.typicode.com和您的options.path应该是您要使用的查询字符串(URL参数)。

当前您正在呼叫velodrome.usefixie.comhttp://jsonplaceholder.typicode.com{your req.path}:80

看看这些:

Node.js docs, http.get

还有这个

How to make a http request

还要从npm中检出 request axios ,它们是为简化Node中的http请求而制作的库。