Axios从本地主机获取对外部网站的请求被拒绝

时间:2019-02-18 22:33:30

标签: javascript http express axios

我正试图通过GET request访问某个外部网站,以最终获取一些信息。我的axios GET request导致连接错误,我认为这可能是由于我从express上运行的localhost服务器发出请求所致。我在package.json中将代理地址设置为"proxy": "http://localhost:8000",,并在服务器中安装并要求安装cors。尽管服务器正在port上运行,但在错误对象80属性中的值为8000

我只是在测试本地计算机上当前的路由,但是当这些请求是从生产环境中部署的服务器发出时,我会遇到这个问题吗?

感谢您的帮助。

server.js

const express = require('express');
const path = require('path');
const cors = require('cors');
const axios = require('axios');

const app = express();

const port = process.env.PORT || 8000;

// MiddleWare
app.use(cors());

app.use('/', express.static(path.join(__dirname, './client/public')));

app.get('/url', (req, res) => {
  const url = req.query.url;

  axios
    .get(url)
    .then(html => {
      res.send(html);
    })
    .catch(err => {
      console.log(err);
    });
});

app.listen(port, () => console.log(`Server doin it's thing on port ${port}...`));

轴错误对象

{ Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1158:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'www.marlindalpozzo.com',
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      { response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { maxRedirects: 21,
        maxBodyLength: 10485760,
        protocol: 'http:',
        path: 'www.marlindalpozzo.com',
        method: 'get',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: null,
        port: null,
        nativeProtocols: [Object],
        pathname: 'www.marlindalpozzo.com' },
     _ended: true,
     _ending: true,
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'GET www.marlindalpozzo.com HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: localhost\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: 'www.marlindalpozzo.com',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http:www.marlindalpozzo.com' },
  response: undefined }

1 个答案:

答案 0 :(得分:0)

我想必须为URL加上https://作为绝对地址的前缀,否则它假定它是服务器位置的相对地址。

我添加了它只是为了检查http是否带有前缀,否则添加它:

const prefix = url.slice(0, 4);
if (prefix !== 'http') {
  url = `https://${url}`;
}