source

CORS를 사용하여 JavaScript Google Places API 요청을 구현하는 방법

factcode 2023. 3. 20. 23:36
반응형

CORS를 사용하여 JavaScript Google Places API 요청을 구현하는 방법

이 작업을 어떻게 해야 하는지 정말 이해할 수 없습니다.

var requestURL = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw';

console.log(requestURL);

$.getJSON( requestURL, function( data ) {
  // data
  console.log(data);
});

및 내 HTML 파일:

  <body>

        <script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
        <script src="main.js" charset="utf-8"></script>   
  </body>

요청된 리소스에 항상 No 'Access-Control-Allow-Origin' 헤더가 표시됩니다.메시지...브라우저에서 https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw에 접속해도 적절한 JSON이 반환됩니다.

나는 CORS가 여기서 나를 도울 수 있다고 믿게 되었다.난 CORS를 이해할 수 없어.제발, 누가 좀 도와주실 수 있나요?이걸 작동시키려면 무엇을 바꿔야 할까요?

감사해요.

Google Places API 웹 서비스를 클라이언트 측에서 사용하려고 하는데, 이 웹 서비스는 서버 측 응용 프로그램용으로 설계되었습니다.그렇기 때문에 서버가 적절한 CORS 응답 헤더를 설정하지 않았을 수 있습니다.

Place Details 문서의 시작 부분에 있는 Notes에 설명된 대로 Google Maps JavaScript API의 Places Library를 사용해야 합니다.

클라이언트측 애플리케이션을 빌드하고 있는 경우는, Google Places API for Android, Google Places API for iOS, 및 Google Maps JavaScript API의 Places Library를 참조해 주세요.

참고: 먼저 Google Developer Console에서 Google Maps JavaScript API를 활성화해야 합니다.

다음은 설명서의 예에 따라 플레이스 세부 정보를 가져올 수 있는 방법입니다.

<head>
    <script type="text/javascript">
        function logPlaceDetails() {
          var service = new google.maps.places.PlacesService(document.getElementById('map'));
          service.getDetails({
            placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
          }, function (place, status) {
            console.log('Place details:', place);
          });
        }
    </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw&libraries=places&callback=logPlaceDetails"></script>
</head>
<body>
    <div id="map"></div>
</body>

콘솔에 Google Place 세부 정보 출력

@rd3n은 Google Maps의 SDK를 사용하는 이유에 대해 이미 답변했지만, 웹 앱(재사용 코드, forexemple)에서 SDK 대신 API를 사용해야 하는 경우 CORS를 사용하여 건너뛸 수 있습니다.proxy파라미터를 지정합니다.

const GMAPS_PLACES_AUTOCOMPLETE_URL = (
  process.env.NODE_ENV === 'production'
    ? 'https://maps.googleapis.com/maps/api/place/autocomplete/json'
    : 'place-api' // on development, we'll use the Webpack's dev server to redirect the request

const urlParams = new URLSearchParams([
  ...
])

const response = await fetch(
  `${GMAPS_PLACES_AUTOCOMPLETE_URL}?${urlParams}`,
  { method: 'GET' }
)

그리고 너의 위에webpack.config.js...

module.exports = {
  devServer: {
    proxy: {
      '/place-api': {
        target: 'https://maps.googleapis.com/maps/api/place/autocomplete/json',
        changeOrigin: true,
        pathRewrite: { '^/place-api': '' }
      }
    }
  }
}

이것은 오래된 질문이라는 것을 알고 있습니다.이 질문에 대한 직접적인 답변은 아닐지도 모릅니다만, 만약 누군가가 이 트릭을 사용할 수 있다면, 저는 항상 PHP를 사용하여 이 문제를 해결하여 나만의 API를 만들고 JavaScript를 사용하여 새로 만든 API를 가져오고 싶습니다.

1# api.php 파일을 만듭니다.

<?php
$google_URL = 'https://maps.googleapis.com/maps/api/place/details/json';
$api = 'YOUR_GOOGLE_API';
$place = 'PLACE_ID';    
$field = [
    'user_ratings_total',
    'rating'
];
    
$fields =  join(",", $field);
$result_url = $google_URL.'?placeid='.$place.'&fields='.$fields.'&key='.$api;
$result_content = file_get_contents($result_url);
$json_data = json_decode($result_content, true);

if ( isset($json_data) && $json_data['status'] === 'OK' ) {
    echo json_encode($json_data['result']);
}else {
    echo json_encode($json_data['error_message']);
}

header("content-type: application/json");

2# script.js 파일을 만듭니다.

const url = './api.php';
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))

입력한 것과 동일한 URL을 사용하여 순수 프런트 엔드(React)를 위한 것이지만, 보안성이 낮은 솔루션을 위한 것입니다.

var requestURL = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw';

url '에서 다음 항목을 삭제하고 패키지에 프록시 라인을 만듭니다.json:

"proxy": "https://maps.googleapis.com/maps/api/place"

그런 다음 Google 문서를 따르면 다음 코드가 표시됩니다(어디서 api를 가져오든).

var axios = require('axios');

var config = {
  method: 'get',
  url: '/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=AIzaSyAW4CQp3KxwYkrHFZERfcGSl--rFce4tNw', //the rest of your url
  secure: false //important
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

언급URL : https://stackoverflow.com/questions/42180788/how-to-use-cors-to-implement-javascript-google-places-api-request

반응형