javascript - მიღება ECONNREFUSED ზარის დროს გარე API-ს NextJS აპლიკაციიდან, რომელიც იყენებს Auth0


მე ამჟამად დავამატე Auth0 ავთენტიფიკაცია ჩემს NextJS აპლიკაციაში მათი დოკუმენტაციის მიხედვით და ვცდილობ დავუკავშირდე გარე ExpressJS აპლიკაციას მათი დოკუმენტაციის მიხედვით: https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#access-an-external-api-from-an-api-route.

მე მაქვს NextJS რომელიც მუშაობს პორტზე 3000 და Express რომელიც მუშაობს პორტზე 3001.

ჩემი Express სერვერი არის დაყენებული ასე:

const jwtCheck = expressjwt({
    secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: process.env.AUTH0_JWKS_URI as string,
    }) as GetVerificationKey,

    audience: process.env.AUTH0_AUDIENCE as string,
    issuer: process.env.AUTH0_ISSUER as string,
    algorithms: ['RS256'],
})

app.use(jwtCheck)

როცა მე ვცდილობ გაუკვალავი მოთხოვნის გაგზავნას ჩემს NextJS აპლიკაციიდან ექსტერნალურ API-ზე, ვიღებ UnauthorizedError: No authorization token was found error, რაც უზრუნველყოფს, რომ ყველაფერი მუშაობს. თუ ვაკომენტარებ app.use(jwtCheck), მოთხოვნები წარმატებულია, რადგან ავტორიზაციის შემოწმება არ ხდება.

ჩემი NextJS აპლიკაცია ასე მაქვს მოწყობილი:

// [...auth0].ts


import { handleAuth, handleLogin } from '@auth0/nextjs-auth0'

export default handleAuth({
    login: handleLogin({
        authorizationParams: {
            audience: process.env.AUTH0_AUDIENCE, // or AUTH0_AUDIENCE
            // Add the `offline_access` scope to also get a Refresh Token
            scope: 'openid profile email read:trips', // or AUTH0_SCOPE
        },
    }),
})


// /api/trips.ts


import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0'

const apiURL = process.env.NEXT_PUBLIC_SERVER_URL

export default withApiAuthRequired(async function trips(req, res) {
    // If your access token is expired and you have a refresh token
    // `getAccessToken` will fetch you a new one using the `refresh_token` grant
    const { accessToken } = await getAccessToken(req, res, {
        scopes: ['read:trips'],
    })

    const response = await fetch(`${apiURL}/trips`, {
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Accept: 'application/json',
            Authorization: `Bearer ${accessToken}`,
        },
    })

    const trips = await response.json()
    res.status(200).json(trips)
})

// /pages/trips/index.tsx

const TripsPage = (props: InferGetServerSidePropsType<typeof getServerSideProps>) => {
    if (!props.user) return <div>User error!</div>


    return (
        <div>
            // components that use the fetched data
        </div>
    )
}


export const getServerSideProps = withPageAuthRequired({
    async getServerSideProps() {

        const { data } = await axios.get('/api/trips')

        try {
            return {
                props: {
                    data: data,
                },
            }
        } catch (e) {
            return {
                notFound: true,
            }
        }
    },
})

export default TripsPage

თუმცა, როდესაც ვცდილობ შევიდე http://localhost:3000/trips გვერდზე შესვლის შემდეგ, მივიღებ შეცდომას:

GET http://localhost:3000/trips 500 (Internal Server Error)
Uncaught Error: connect ECONNREFUSED ::1:80
    at <unknown> (Error: connect ECONNREFUSED ::1:80)
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16)

გამოდის, რომ მოთხოვნა საერთოდ არ გადის ჩემს NextJS აპლიკაციაში. ჩანს, რომ შიდა API ზარი ვერ შესრულდა. თუმცა, თუ პირდაპირ გადავდივარ http://localhost:3000/api/trips, მე მიღებ პასუხს JSON მონაცემებით და თუ console.log-ში ვნახავ accessToken, ის ვალიდურია. ასე რომ, ავტენტიფიკაცია მუშაობს, მაგრამ პრობლემა არის იმ გვერდზე, რომელიც გამოძახებს NextJS proxy API-ს, რომელიც თავის მხრივ გამოძახებს ჩემს ExpressJS API-ს.

NextJS კონსოლზე სრული შეცდომის ლოგი არის:

error - AxiosError: connect ECONNREFUSED ::1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
  port: 80,
  address: '::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] },
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.27.2'
    },
    method: 'get',
    url: '/api/trips',
    data: undefined
  },
  request: <ref *1> 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: '/api/trips',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: null,
      port: null,
      nativeProtocols: [Object],
      pathname: '/api/trips'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: true,
      socket: [Socket],
      _header: 'GET /api/trips HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.27.2\r\n' +
        'Host: localhost\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/trips',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *1],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: true,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http:/api/trips',
    [Symbol(kCapture)]: false
  },
  page: '/trips'
}

გინდა იფიქრო, რა ხდება აქ?

პასუხი #1

ცადე გამოიყენო 127.0.0.1 localhost-ის ნაცვლად. მე თვითსაც მქონდა იგივე პრობლემა.

პასუხი #2

პრობლემა იყო ის, რომ ჩვენ არ გვაქვს უფლება დავუკავშირდეთ შიდა NextJS /api/ როუტს getServerSideProps-ში. ჩვენ უნდა დავუკავშირდეთ პირდაპირ გარე API-ს და არა შიდა /api პროქსის საშუალებით.

მეტი ინფორმაცია: https://github.com/auth0/nextjs-auth0/issues/995