Home > database >  AxiosError: connect ECONNREFUSED 127.0.0.1:80
AxiosError: connect ECONNREFUSED 127.0.0.1:80

Time:07-20

I got these errors on terminal

Server on port 3000

node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^
AxiosError: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
  port: 80,
  address: '127.0.0.1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -4078,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] {
        LINE_BREAK: '\r\n',
        DEFAULT_CONTENT_TYPE: 'application/octet-stream'
      }
    },
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'axios/0.27.2',
      'Content-Length': 315
    },
    auth: {
      username: '',
      password: ''
    },
    method: 'post',
    url: '${PAYPAL_API}/v2/checkout/orders',
    data: '{"intent":"CAPTURE","purchase_units":[{"amount":{"currency_code":"USD","value":"2"},"description":"suscription"}],"application_context":{"brand_name":"pomoworko.app","landing_page":"LOGIN","user_action":"PAY_NOW","return_url":"http://localhost:4000/capture-order","cancel_url":"http://localhost:4000/cancel-order"}}'
  },
  request: <ref *2> 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,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: '${PAYPAL_API}/v2/checkout/orders',
      method: 'POST',
      headers: {
        Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        'User-Agent': 'axios/0.27.2',
        'Content-Length': 315
      },
      agent: undefined,
      agents: { http: undefined, https: undefined },
      auth: '',
      hostname: null,
      port: null,
      nativeProtocols: {
        'http:': {
          _connectionListener: [Function: connectionListener],
          METHODS: [
            'ACL',         'BIND',       'CHECKOUT',
            'CONNECT',     'COPY',       'DELETE',
            'GET',         'HEAD',       'LINK',
            'LOCK',        'M-SEARCH',   'MERGE',
            'MKACTIVITY',  'MKCALENDAR', 'MKCOL',
            'MOVE',        'NOTIFY',     'OPTIONS',
            'PATCH',       'POST',       'PROPFIND',
            'PROPPATCH',   'PURGE',      'PUT',
            'REBIND',      'REPORT',     'SEARCH',
            'SOURCE',      'SUBSCRIBE',  'TRACE',
            'UNBIND',      'UNLINK',     'UNLOCK',
            'UNSUBSCRIBE'
          ],
          STATUS_CODES: {
            '100': 'Continue',
            '101': 'Switching Protocols',
            '102': 'Processing',
            '103': 'Early Hints',
            '200': 'OK',
            '201': 'Created',
            '202': 'Accepted',
            '203': 'Non-Authoritative Information',
            '204': 'No Content',
            '205': 'Reset Content',
            '206': 'Partial Content',
            '207': 'Multi-Status',
            '208': 'Already Reported',
            '226': 'IM Used',
            '300': 'Multiple Choices',
            '301': 'Moved Permanently',
            '302': 'Found',
            '303': 'See Other',
            '304': 'Not Modified',
            '305': 'Use Proxy',
            '307': 'Temporary Redirect',
            '308': 'Permanent Redirect',
            '400': 'Bad Request',
            '401': 'Unauthorized',
            '402': 'Payment Required',
            '403': 'Forbidden',
            '404': 'Not Found',
            '405': 'Method Not Allowed',
            '406': 'Not Acceptable',
            '407': 'Proxy Authentication Required',
            '408': 'Request Timeout',
            '409': 'Conflict',
            '410': 'Gone',
            '411': 'Length Required',
            '412': 'Precondition Failed',
            '413': 'Payload Too Large',
            '414': 'URI Too Long',
            '415': 'Unsupported Media Type',
            '416': 'Range Not Satisfiable',
            '417': 'Expectation Failed',
            '418': "I'm a Teapot",
            '421': 'Misdirected Request',
            '422': 'Unprocessable Entity',
            '423': 'Locked',
            '424': 'Failed Dependency',
            '425': 'Too Early',
            '426': 'Upgrade Required',
            '428': 'Precondition Required',
            '429': 'Too Many Requests',
            '431': 'Request Header Fields Too Large',
            '451': 'Unavailable For Legal Reasons',
            '500': 'Internal Server Error',
            '501': 'Not Implemented',
            '502': 'Bad Gateway',
            '503': 'Service Unavailable',
            '504': 'Gateway Timeout',
            '505': 'HTTP Version Not Supported',
            '506': 'Variant Also Negotiates',
            '507': 'Insufficient Storage',
            '508': 'Loop Detected',
            '509': 'Bandwidth Limit Exceeded',
            '510': 'Not Extended',
            '511': 'Network Authentication Required'
          },
          Agent: [Function: Agent] { defaultMaxSockets: Infinity },
          ClientRequest: [Function: ClientRequest],
          IncomingMessage: [Function: IncomingMessage],
          OutgoingMessage: [Function: OutgoingMessage],
          Server: [Function: Server],
          ServerResponse: [Function: ServerResponse],
          createServer: [Function: createServer],
          validateHeaderName: [Function: __node_internal_],
          validateHeaderValue: [Function: __node_internal_],
          get: [Function: get],
          request: [Function: request],
          maxHeaderSize: [Getter],
          globalAgent: [Getter/Setter]
        },
        'https:': {
          Agent: [Function: Agent],
          globalAgent: Agent {
            _events: [Object: null prototype],
            _eventsCount: 2,
            _maxListeners: undefined,
            defaultPort: 443,
            protocol: 'https:',
            options: [Object: null prototype],
            requests: [Object: null prototype] {},
            sockets: [Object: null prototype] {},
            freeSockets: [Object: null prototype] {},
            keepAliveMsecs: 1000,
            keepAlive: false,
            maxSockets: Infinity,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            maxTotalSockets: Infinity,
            totalSocketCount: 0,
            maxCachedSessions: 100,
            _sessionCache: [Object],
            [Symbol(kCapture)]: false
          },
          Server: [Function: Server],
          createServer: [Function: createServer],
          get: [Function: get],
          request: [Function: request]
        }
      },
      pathname: '${PAYPAL_API}/v2/checkout/orders'
    },
    _ended: false,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 315,
    _requestBodyBuffers: [
      {
        data: Buffer(315) [Uint8Array] [
          123,  34, 105, 110, 116, 101, 110, 116,  34,  58,  34,  67,
           65,  80,  84,  85,  82,  69,  34,  44,  34, 112, 117, 114,
           99, 104,  97, 115, 101,  95, 117, 110, 105, 116, 115,  34,
           58,  91, 123,  34,  97, 109, 111, 117, 110, 116,  34,  58,
          123,  34,  99, 117, 114, 114, 101, 110,  99, 121,  95,  99,
          111, 100, 101,  34,  58,  34,  85,  83,  68,  34,  44,  34,
          118,  97, 108, 117, 101,  34,  58,  34,  50,  34, 125,  44,
           34, 100, 101, 115,  99, 114, 105, 112, 116, 105, 111, 110,
           34,  58,  34, 115,
          ... 215 more items
        ],
        encoding: undefined
      }
    ],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: <ref *1> ClientRequest {
      _events: [Object: null prototype] {
        response: [Function: bound onceWrapper] {
          listener: [Function (anonymous)]
        },
        abort: [Function (anonymous)],
        aborted: [Function (anonymous)],
        connect: [Function (anonymous)],
        error: [Function (anonymous)],
        socket: [Function (anonymous)],
        timeout: [Function (anonymous)]
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: true,
      _closed: false,
      socket: Socket {
        connecting: false,
        _hadError: true,
        _parent: null,
        _host: 'localhost',
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          destroyed: true,
          errored: Error: connect ECONNREFUSED 127.0.0.1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: false,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          connect: [ [Function], [Function], [Function] ],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],       
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          drain: [Function: ondrain]
        },
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: false,
          needDrain: false,
          ending: false,
          ended: false,
          finished: false,
          destroyed: true,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 766,
          writing: true,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: [Function (anonymous)],
          writelen: 766,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          errored: Error: connect ECONNREFUSED 127.0.0.1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: [
          {
            chunk: 'POST ${PAYPAL_API}/v2/checkout/orders HTTP/1.1\r\n'      
              'Accept: application/json, text/plain, */*\r\n'  
              'Content-Type: application/json\r\n'  
              'User-Agent: axios/0.27.2\r\n'  
              'Content-Length: 315\r\n'  
              'Host: localhost\r\n'  
              'Authorization: Basic QVd0clhhNDB1N2JIMnlwR09mS09qVVlET2E5bDQ5Tzk3djVOTV92bUxKZkVkTXd2QXE0S1lWXzZzS2FHdE9CaElyWk50TlRod0JIaEQyNmI6RUpiSkk4TzNQMWVLUTlRcWhzZ1c4Zm9oUVdhMzRna0g2VGZwSC05QzVwaGFKX1JEbElReFNIWkE4ekxOSEVnMDFLRlVUY1NZbGczQlVhclc=\r\n'  
              'Connection: close\r\n'  
              '\r\n',
            encoding: 'latin1',
            callback: [Function: nop]
          },
          {
            chunk: [Buffer [Uint8Array]],
            encoding: 'buffer',
            callback: [Function (anonymous)]
          },
          allBuffers: false
        ],
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 14,
        [Symbol(kHandle)]: null,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kSetNoDelay)]: false,
        [Symbol(kSetKeepAlive)]: true,
        [Symbol(kSetKeepAliveInitialDelay)]: 60,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0
      },
      _header: 'POST ${PAYPAL_API}/v2/checkout/orders HTTP/1.1\r\n'          
        'Accept: application/json, text/plain, */*\r\n'  
        'Content-Type: application/json\r\n'  
        'User-Agent: axios/0.27.2\r\n'  
        'Content-Length: 315\r\n'  
        'Host: localhost\r\n'  
        'Authorization: Basic '  
        'Connection: close\r\n'  
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: Agent {
        _events: [Object: null prototype] {
          free: [Function (anonymous)],
          newListener: [Function: maybeEnableKeylog]
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: 'http:',
        options: [Object: null prototype] { path: null },
        requests: [Object: null prototype] {},
        sockets: [Object: null prototype] { 'localhost:80:': [ [Socket] ] },     
        freeSockets: [Object: null prototype] {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        scheduling: 'lifo',
        maxTotalSockets: Infinity,
        totalSocketCount: 1,
        [Symbol(kCapture)]: false
      },
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '${PAYPAL_API}/v2/checkout/orders',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *2],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype] {
        accept: [ 'Accept', 'application/json, text/plain, */*' ],
        'content-type': [ 'Content-Type', 'application/json' ],
        'user-agent': [ 'User-Agent', 'axios/0.27.2' ],
        'content-length': [ 'Content-Length', 315 ],
        host: [ 'Host', 'localhost' ],
        authorization: [
          'Authorization',
          'Basic '
        ]
      }
    },
    _currentUrl: '${PAYPAL_API}/v2/checkout/orders',
    [Symbol(kCapture)]: false
  }
}
[nodemon] app crashed - waiting for file changes before starting...

to summarize these are the errors:

node:internal/process/promises:279 triggerUncaughtException(err, true /* fromPromise */); ^ AxiosError: connect ECONNREFUSED 127.0.0.1:80 errored: Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)

This is my code:

payment.controllers.js

import axios from "axios";
import {PAYPAL_API, PAYPAL_API_CLIENT, PAYPAL_API_SECRET} from '../config'

export const createOrder = async (req, res) => {
    const order = {
        intent : 'CAPTURE',
        purchase_units: [
            {
                amount: {
                    currency_code:"USD",
                    value: '2'
                },
                description: "suscription"
            },
        ],
        application_context: {
            brand_name: "pomoworko.app",
            landing_page: "LOGIN",
            user_action: "PAY_NOW",
            return_url: 'http://localhost:4000/capture-order',
            cancel_url: 'http://localhost:4000/cancel-order'
        }
    };

    const response = await axios.post('${PAYPAL_API}/v2/checkout/orders', order, {
        auth: {
            username: PAYPAL_API_CLIENT,
            password: PAYPAL_API_SECRET
        }
    });

    console.log(response)

    res.send('creating order');
}

export const captureOrder = (req, res) => {
    res.send('capture an order')
}

export const cancelOrder = (req, res) => {
    res.send('cancel an order')
}

config.js

export const PORT = 3000

index.js

import express from 'express';
import morgan from "morgan";
import {PORT} from './config'
import paymentRoutes from './routes/payment.routes'

const app = express();

app.use(morgan('dev'));

app.use(paymentRoutes);

app.listen(PORT);
console.log("Server on port", PORT);

package.json

{
  "name": "nodeks_paypal",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/index.js --exec babel-node"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.18.9",
    "@babel/core": "^7.18.9",
    "@babel/node": "^7.18.9",
    "@babel/preset-env": "^7.18.9",
    "nodemon": "^2.0.19"
  }
}

I also tried this:

http://localhost:3000/create-order http://localhost:4000/create-order

But, dont wotk it show me this:

enter image description here enter image description here

payment.routes

import {Router} from 'express'
import {
    createOrder,
    captureOrder, 
    cancelOrder} 
    from '../controllers/payment.controller'

const router = Router();

router.get('/create-order', createOrder);

router.get('/capture-order', captureOrder);

router.get('/cancel-order', cancelOrder);


export default router;

How to solve this issue?

CodePudding user response:

You're defining the paypal url as '${PAYPAL_API}/v2/checkout/orders', which will be used exactly as-is and won't actually replace the PAYPAL_API variable due to the single quotes. You should use back ticks instead as template literals (see more info here) like this:

axios.post(`${PAYPAL_API}/v2/checkout/orders`, ...
  • Related