왜 Nest.JS 까지 설정을 하게되었는가?
- 아래 코드와 같이 리액트에서 즉 클라이언트에서 바로 naver maps Geocoding api를 호출을 하였는데 401 error가 발생하였다.
- 검색해본 결과 naver에서 클라이언트에서 바로 api 호출하는 방식은 금지하고 있다고 한다.
- proxy server를 이용하던 backend를 만들어 호출을 하라는 것인데 Nest.JS를 이용하여 백엔드로 하기로 했다.
import { useMutation } from '@tanstack/react-query';
import axios from 'axios';
import { useCallback } from 'react';
export const useGetGeocode = () => {
const mutation = useMutation({
mutationFn: async (searchKeyword: string) =>
axios.get(`https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=${searchKeyword}`, {
headers: {
'X-NCP-APIGW-API-KEY-ID': process.env.REACT_APP_NAVER_CLIENT_ID,
'X-NCP-APIGW-API-KEY': process.env.REACT_APP_NAVER_CLIENT_SECRET,
},
}),
});
return useCallback(async (searchKeyword: string) => await mutation.mutateAsync(searchKeyword), [mutation]);
};
const btn_search_onClick = (data: searchKeywordInterface) => {
if (data.searchKeyword === '') {
alert('검색어를 입력하세요.');
return;
}
getGeocode(data.searchKeyword)
.then((response) => {
console.log('response', response.data);
})
.catch();
};
Nest.JS 설정부터 시작
main.ts
- 4100 포트로 오픈하고 cors 설정까지 완료.
- cors에 대해 다시 공부하게 되었다
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.enableCors({
origin: 'http://localhost:3000',
});
await app.listen(4100);
}
bootstrap();
app.module.ts
- .env 파일을 불러오기 위해 ConfigModule 설치 및 설정
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GeocodingModule } from './modules/naver-mpas/geocoding/geocoding.module';
import { ConfigModule } from '@nestjs/config';
import { configModuleConfig } from './config';
@Module({
imports: [ConfigModule.forRoot(configModuleConfig), GeocodingModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { ConfigModuleOptions } from '@nestjs/config';
export const configModuleConfig: ConfigModuleOptions = {
envFilePath: '.naver-maps.env',
isGlobal: true,
};
controller 설정
import { Controller, Get, Query, Req } from '@nestjs/common';
import { GeocodingService } from './geocoding.service';
@Controller('geocoding')
export class GeocodingController {
constructor(private readonly geocodingService: GeocodingService) {}
@Get()
getGeocoding(@Query() query: { searchKeyword: string }) {
return this.geocodingService.getGeocoding(query.searchKeyword);
}
}
service 설정
- controller 에서 받은 query를 service로 가져와 naver-maps queryString으로 사용
- 성공하면 response.data 반환
- service에서 axios 호출하는 방법이 맞는지는 모르겠습니다...
import { Injectable } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class GeocodingService {
async getGeocoding(searchKeyword: string) {
return axios
.get(
`https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query=${searchKeyword}`,
{
headers: {
'X-NCP-APIGW-API-KEY-ID': process.env.NAVER_CLIENT_ID,
'X-NCP-APIGW-API-KEY': process.env.NAVER_CLIENT_SECRET,
},
},
)
.then((response) => {
return response.data;
})
.catch((error) => {
console.log('error', error);
});
}
}
결론 성공
