inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Tìm hiểu mã hóa DO IT front-end trong khi tạo nó (Next.js, Typescript)

Thêm mã quản trị căn cứ hỏa lực

thunder client로 get 요청시 무한로딩

Đã giải quyết

1157

fe

25 câu hỏi đã được viết

0

안녕하세요. thunder client로 get 요청시 무한로딩이 됩니다.

localhost:3000/api/hello에 대한 요청이 되지 않습니다.

다른 open api 요청을 쏴봤는데요. 그건 됩니다.

혹시 원인이 무엇일까요?

스크린샷 2023-04-23 오후 4.16.00.png개발 환경은 실행중입니다.

폴더 구조입니다.

스크린샷 2023-04-23 오후 4.18.07.png

 

아래는 코드입니다.

// hello.ts

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction

import { NextApiRequest, NextApiResponse } from 'next';
import FirebaseAdmin from '@/models/firebase_admin';

export default function handler(_: NextApiRequest, res: NextApiResponse) {
  FirebaseAdmin.getInstance().Firebase.collection('test');
  res.status(200).json({ name: 'John Doe' });
}

 

// firebase_admin.ts

import * as admin from 'firebase-admin';

interface Config {
  credential: {
    privateKey: string;
    clientEmail: string;
    projectId: string;
  };
}

/** 싱글톤 패턴을 이용해서 어디서든 같은 인스턴스를 불러낼 수 있도록 한다. */
export default class FirebaseAdmin {
  public static instance: FirebaseAdmin;

  /** 초기화 여부 */
  private init = false;

  /** 인스턴스를 반환하는 메서드 */
  public static getInstance(): FirebaseAdmin {
    if (FirebaseAdmin.instance === undefined || FirebaseAdmin.instance === null) {
      /** 초기화 진행 */
      FirebaseAdmin.instance = new FirebaseAdmin();
      /** 환경을 초기화한다. */
      FirebaseAdmin.instance.bootstrap();
    }
    return FirebaseAdmin.instance;
  }

  /** 환경을 초기화할 때 사용할 메서드 */
  private bootstrap(): void {
    /** 등록되어 있는 앱의 갯수가 0이 아니어야 앱이 존재함을 의미한다. */
    const haveApp = admin.apps.length !== 0;
    if (haveApp) {
      this.init = true;
      return;
    }

    /** config를 활용해서 초기화한다. */
    const config: Config = {
      credential: {
        /** process.env.로 환경변수에 접근하여 각 값들을 받아온다.
         * 각 갑들은 undefined일 수 있으므로, 값이 없을 경우 빈 문자열을 할당한다.
         */
        projectId: process.env.projectid || '',
        clientEmail: process.env.clientEmail || '',

        /**
         * privateKey는 원래 개행이 들어간 여러 줄 짜리 텍스트인데, 반환할 때는 json에서는 그렇게 표현할 수 없기 때문에 한 줄이 된다.
         * 그 한줄짜리 json을 원래대로 개행이 들어가도록 임의로 다시 개행문자를 넣어주는 것이다.
         */
        privateKey: (process.env.privatekey || '').replace(/\\n/g, '\n'),
      },
    };
    admin.initializeApp({ credential: admin.credential.cert(config.credential) });
    console.info('bootstrap firebase admin');
  }

  /** firestore를 반환 */
  public get Firebase(): FirebaseFirestore.Firestore {
    if (this.init === false) {
      this.bootstrap();
    }
    return admin.firestore();
  }

  public get Auth(): admin.auth.Auth {
    if (this.init === false) {
      this.bootstrap();
    }
    return admin.auth();
  }
}

next.js

Câu trả lời 1

1

totuworld

안녕하세요 fe님.

 

코드 상으로는 안될 이유가 없어보이네요.

올려주신 스크린샷보면 package-lock.json이 보이더라고요. npm 과 yarn을 같이 쓰신듯해요.

package-lock.json 삭제하시고, node_modules 폴더도 삭제한 뒤
yarn 으로 패키지 재설치 하신 뒤에 실행해보시겠어요?

 

 

그리고 브라우저로 localhost:3000 진입은 되는지도 체크 부탁드립니다.

post하는 경우에 uid 설정

0

139

1

vscode bgColor 바로 표시되기 설정방법 및 chakra-ui img src 설정관련

0

508

2

클래스 방식말고 (2)

0

327

1

클래스 방식말고

0

312

1

배포 후 오류

0

1150

3

const resp = await fetch(`/api/messages.list?uid=${uid}`)가 404에러가 뜹니다

0

438

1

localhost:3000/api/user.info/totuworld 404 에러가 뜹니다.

0

437

3

사용자를 찾을 수 없다.

0

378

1

2. 사용자 API 만들기 => 강의는 짧지만 백엔드 api 만드는 기본 내용 다 들어가 있음 주의하세요!!

0

379

1

toast 처리부터 오류발생

0

600

3

FirebaseError: Firebase: Error (auth/invalid-api-key).

0

1831

3

Vercel 배포 후 thumbnail api 에러 발생합니다.

0

707

1

[~~].toStr에 대해

0

248

1

firebase admin 환경 초기화 하는 부분 질문입니다.

0

406

1

/api/[screenName].ts API에 대해 문의드립니다.

0

340

1

구글 가입 버튼 오류: redirect_uri_mismatch

0

537

1

mac m1 node 14버전 설치 에러

0

642

1

전체 예제 소스좀 올려주세요

0

445

1

R_CONNECTION_TIMED_OUT 오류

0

625

1

로그인 버튼 클릭시 auth/auth-domain-config-required 에러 발생

0

710

1

@types/react를 인식하지 못하는 에러

0

2831

3

firebase auth 인증 질문

0

1210

1

router 관련 질문입니다.

0

387

1

자동 줄바꿈

0

383

1