我尝试通过具有代理域的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();
});
答案 0 :(得分:0)
您的options.host
应该是您要呼叫的远程主机,例如http://jsonplaceholder.typicode.com
和您的options.path
应该是您要使用的查询字符串(URL参数)。
当前您正在呼叫velodrome.usefixie.comhttp://jsonplaceholder.typicode.com{your req.path}:80
。
看看这些:
还有这个
还要从npm中检出 request 和 axios ,它们是为简化Node中的http请求而制作的库。