728x90
아래와 같이 정리된 교육용 자료로 만들 수 있어.
📌 크롬에서 로컬 파일의 위치 권한 유지 방법
1️⃣ 크롬 실행 옵션 활용
(1) --unsafely-treat-insecure-origin-as-secure 플래그 사용
크롬을 종료한 후, 아래 명령어로 실행하면 로컬 파일을 안전한 출처로 간주할 수 있음.
chrome.exe --unsafely-treat-insecure-origin-as-secure="file://your-local-file-path" --user-data-dir=/tmp/test
- Windows: cmd 또는 PowerShell에서 실행
- Mac/Linux: 터미널에서 실행
- your-local-file-path 부분을 실제 파일 경로로 변경
- --user-data-dir 옵션을 추가하면 충돌 방지
(2) 크롬 플래그 설정 변경
- 크롬 주소창에 chrome://flags/#unsafely-treat-insecure-origin-as-secure 입력
- 해당 옵션을 Enabled로 변경
- file://your-local-file-path 입력 후 크롬 재시작
2️⃣ HTTPS 환경에서 실행 (추천)
로컬 파일은 브라우저 보안 정책으로 인해 위치 권한을 자동 허용하기 어려움.
로컬 HTTP/HTTPS 서버에서 실행하면 해결 가능.
(1) Python HTTP 서버 사용
python3 -m http.server 8000
- http://localhost:8000/your-local-file.html 에 접속하여 테스트 가능
- HTTPS가 필요한 경우 mkcert 등을 활용해 로컬 SSL 인증서 생성 가능
(2) NestJS에서 HTTPS 서버 실행
① SSL 인증서 생성
openssl req -nodes -new -x509 -keyout server.key -out server.cert
② main.ts 수정
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { readFileSync } from 'fs';
async function bootstrap() {
const httpsOptions = {
key: readFileSync('server.key'),
cert: readFileSync('server.cert'),
};
const app = await NestFactory.create(AppModule, { httpsOptions });
app.useGlobalPipes(
new ValidationPipe({
transform: true,
stopAtFirstError: true,
}),
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
이제 https://localhost:3000 에서 실행 가능.
3️⃣ HTML에서 위치 권한 요청
<button id="getLocation">위치 요청</button>
<p id="status"></p>
<script>
document.getElementById('getLocation').addEventListener('click', () => {
if (navigator.geolocation) {
navigator.permissions.query({ name: 'geolocation' }).then(result => {
if (result.state === 'granted') {
getLocation();
} else if (result.state === 'prompt') {
navigator.geolocation.getCurrentPosition(getLocation, showError);
} else {
alert('위치 권한이 차단됨. 설정에서 허용해야 합니다.');
}
});
}
});
function getLocation() {
navigator.geolocation.getCurrentPosition((position) => {
document.getElementById('status').innerText = `위도: ${position.coords.latitude}, 경도: ${position.coords.longitude}`;
}, showError);
}
function showError(error) {
document.getElementById('status').innerText = `오류 발생: ${error.message}`;
}
</script>
✅ HTTPS 환경에서 실행해야 자동으로 권한 유지됨
4️⃣ NestJS에서 위치 데이터 처리
(1) 컨트롤러 생성 (location.controller.ts)
import { Controller, Post, Body } from '@nestjs/common';
@Controller('location')
export class LocationController {
@Post()
saveLocation(@Body() body: { latitude: number; longitude: number }) {
console.log('받은 위치 데이터:', body);
return { message: '위치 저장 완료', received: body };
}
}
(2) 클라이언트에서 데이터 전송
function getLocation() {
navigator.geolocation.getCurrentPosition((position) => {
const data = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
fetch('https://localhost:3000/location', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => console.log('서버 응답:', data))
.catch(error => console.error('에러 발생:', error));
}, showError);
}
✅ NestJS API와 연동하여 위치 데이터를 저장 가능
🔥 결론
✅ HTTPS 환경에서 실행 (필수!)
✅ HTML에서 navigator.permissions.query() 활용하여 자동 요청
✅ NestJS API 연동하여 위치 데이터 저장 가능
✅ 크롬 정책 변경을 통해 자동 허용 가능 (권장 X)
추가 질문 있으면 알려줘! 🚀
'내일배움 정리 > JS 문법 공부' 카테고리의 다른 글
LocalTunnel을 이용한 로컬 서버 외부 공유 방법 (0) | 2025.02.24 |
---|---|
Nestjs에서 Valkey 쓰기 - *.service.ts (0) | 2025.02.22 |
NestJs 실행 명령어 (0) | 2025.02.20 |
nestJs CURD 레포지토리 (0) | 2025.02.18 |
NestJs - HTTP 예외 처리 클래스 (0) | 2025.02.14 |