首页 > 解决方案 > Axios 在 node.js 中的 url 之前添加 localhost 路径

问题描述

我对 Axios 有疑问。Axios 在 node.js 中的 URL 之前添加了一个 localhost 路径。

这是我的代码:

import VerifyCodes from '../../../model/DatabaseModel/VerifyCodes';
import axios from 'axios';
import qs from 'qs';

const apiUrl = 'https://api.ghasedak.io/v2/verification/send/simple';

let axiosConfig = {
    method: 'post',
    url: apiUrl,
    headers: {
        apikey: 'someNumbers',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: null,
};

let additionalBodyData = {
    template: 'test',
    type: '1',
};

export const generateAuthenticationCode = (receptor) =>
    new Promise(async (resolve, reject) => {
        let code =
            Math.floor(Math.random() * (9999 - 1111 + 1)) + 1111;

        axiosConfig.data = qs.stringify({
            ...additionalBodyData,
            param1: String(code),
            receptor,
        });

        await VerifyCodes.insertOrUpdateNewCode(receptor, code);

        // @ts-ignore
        axios(axiosConfig)
            .catch(reject)
            .then(() => resolve(code));
    });

这是我的错误:

{ Error: connect ECONNREFUSED 127.0.0.1:34773
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 34773,
  config:
   { url: 'https://api.ghasedak.io/v2/verification/send/simple',
     method: 'post',
     data: 'template=test&type=1&param1=2549&receptor=0856',
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/x-www-form-urlencoded',
        apikey: 'apiKey',
        'User-Agent': 'axios/0.21.0',
        'Content-Length': 53,
        host: 'api.ghasedak.io' },
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     maxBodyLength: -1,
     validateStatus: [Function: validateStatus] },
  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,
        autoDestroy: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { maxRedirects: 21,
        maxBodyLength: 10485760,
        protocol: 'http:',
        path: 'https://api.ghasedak.io/v2/verification/send/simple',
        method: 'POST',
        headers: [Object],
        agent: undefined,
        agents: [Object],
        auth: undefined,
        hostname: '127.0.0.1',
        port: '34773',
        nativeProtocols: [Object],
        pathname: 'https://api.ghasedak.io/v2/verification/send/simple' },
     _ended: false,
     _ending: true,
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 53,
     _requestBodyBuffers: [ [Object] ],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 7,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'POST https://api.ghasedak.io/v2/verification/send/simple HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/x-www-form-urlencoded\r\napikey: 3dac6bca51eed0a5f60d0fb3e5f9a230daf62e81aae3e018016f9bc37e4bf8c9\r\nUser-Agent: axios/0.21.0\r\nContent-Length: 53\r\nhost: api.ghasedak.io\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        insecureHTTPParser: undefined,
        path: 'https://api.ghasedak.io/v2/verification/send/simple',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl:
      'http://127.0.0.1:34773/https://api.ghasedak.io/v2/verification/send/simple' },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON] }

如您所见,Axios 在 URL 中添加了http://127.0.0.1:34773/,我确信我没有在我的项目中设置 Axios 默认 baseUrl。

我不知道为什么会这样,也不知道该怎么办!

任何人都可以帮助我吗?

标签: javascriptnode.jsaxiosqstring

解决方案


我试过和你一样的配置,效果很好。看起来你想隐藏一些重要信息,例如 apikey。它们在错误消息中详细显示。


推荐阅读