728x90
반응형

작년에 만든 PASS 인증을 위해

1. AuthReq/index.tsx 에서 returnUrl 과 action 으로 만들고, getServerSideProps 로 받았던 코드가 있었다.

어후,,, 너저분

 

쨋든,, 이런 너저분한 코드가 있었다.

 

이걸 이번에 next.js 14버전이 되면서 app router로 바꿨는데,,

안된다..

인터넷을 겁나게 검색하면

여러가지 말이 나오는데,, 후 다 복붙성이다(개짜증나!)

 

그래서 고민고민 또 고민 했다..

결과

 

기존처럼

form 데이터를 구성하고

action url : 인증 url
return url :`${serverDomain}/api/AuthResult`

로 구성했다.

 

이후

import axios from 'axios';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
    const host = request.headers.get('host');
    const origin = request.headers.get('origin');

    console.log('Host:', host);
    console.log('Origin:', origin);

    const serverDomain = `https://${host}`;

    try {
        const formData = await request.formData();
        const result = Object.fromEntries(formData.entries());

        const stringResult = Object.keys(result).reduce((acc, key) => {
            acc[key] = String(result[key]);
            return acc;
        }, {} as Record<string, string>);


        const authRes = await axios({
            method: 'post',
            url: `${process.env.NEXT_PUBLIC_DEFAULT_API_URL}${process.env.NEXT_PUBLIC_AUTH_RES}`,
            params:stringResult
        });

        if (!authRes.data.authSeq || !authRes.data.encValue) {
            console.error('Missing required fields in authRes:', authRes.data);
            return NextResponse.json({ success: false, error: 'Missing required fields in authRes' }, { status: 400 });
        }

        const sendData = {
            authSeq: authRes.data.authSeq,
            encValue: authRes.data.encValue,
            reqValue: "phone",
        };

        const resGetInfo = await axios.get(`${process.env.NEXT_PUBLIC_DEFAULT_API_URL}${process.env.NEXT_PUBLIC_AUTH_GET_INFO}`, {
            headers: {
                Accept: "application/json",
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            },
            params: sendData
        });

        const results = resGetInfo.data;

        console.log('results', results);

        const queryParams = new URLSearchParams(results).toString();
        const redirectUrl = `${serverDomain}/Auth/AuthRes?${queryParams}`;

        return NextResponse.redirect(redirectUrl);
    } catch (error) {
        console.error('Error processing auth result:', error);
        return NextResponse.json({ success: false, error: 'Failed to process auth result' }, { status: 500 });
    }
}
 

이렇게 되면 내가 데이터 받으려고 만든 /Auth/AuthRes 에서 searchParams로 받는다.

 

이렇게 받은 searchParams는 잘 가공해서 쓴다 :)

나는 어따가 보내버렸다.

  useEffect(() => {
    closeAuthModal();
    if (datas) {
      const dataSend = {
        ...datas,
      };
      window.parent.postMessage(dataSend, "*");
    }
  }, [closeAuthModal, datas]);

 

맞는 방법이 아닐수도 있지만,

만족!

 

프로젝트가 끝나면 리팩토링을 또 시도해봐야겠다.

728x90
반응형

+ Recent posts