简体   繁体   中英

How to send request to google maps API?

I have my key for google maps api and when i write the url in the browser I get the object. Now when I try to send the request from my app I get this error

Request header field Content-Type is not allowed by 
Access-Control-Allow-Headers in preflight response

I do my request with fetch

fetch(url,{
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
    .then(async res => {
          const data = await res.json();
          self.setState({
            Zone: data
          })
        })
        .catch(function(err) {
          console.log('ERROR!!! ' + err.message);
        });`

There is no need to set the header Content-Type in your GET request to Google's API, as you are not sending a POST request with a json body.

And since a request is by default a GET request, you can leave out the options object:

fetch(url)
.then(async res => {
  const data = await res.json()
  self.setState({
    Zone: data
  })
})
.catch(function(err) {
  console.log('ERROR!!! ' + err.message)
})

There are 2 ways how you can solve your error. The first is using a chrome extension to allow CORS: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

The second option is installing the cors npm package and using that inside your javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM