📜  google api 键 localhost 限制 (1)

📅  最后修改于: 2023-12-03 15:01:02.592000             🧑  作者: Mango

Google API Key Localhost Restrictions

There are times when a developer needs to restrict their Google API key to a certain domain. This is done to prevent others from using the API key, thus protecting the developer’s account from being charged with excessive API usage fees.

One of the restrictions that can be applied to a Google API key is to limit it to localhost. This is useful during development since the API key can be accessed only by the developer’s local machine. In this way, the key is protected and its usage is limited only to the developer’s localhost domain.

To enable the localhost restriction, follow these steps:

  1. Go to the Google Cloud Console and select the project for which you want to create a new API key

  2. Click on the “Create Credentials” button and select the “API Key” option

  3. Choose the “HTTP referrers” restriction and enter “localhost/*” in the first line

  4. Save the API key

With the localhost restriction enabled, the API key can now only be used by requests originating from the developer’s localhost domain. Any attempts to use it from other domains will result in a “403 Forbidden” error.

Here is an example of how to use a Google API key with the localhost restriction enabled in JavaScript:

const apiKey = "YOUR_API_KEY_HERE";

// construct the url for the API request
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${apiKey}`;

// make the API request
fetch(url)
  .then(response => response.json())
  .then(data => {
    // handle the API response data here
  })
  .catch(error => {
    // handle any errors here
  });

Be sure to replace “YOUR_API_KEY_HERE” with your actual API key.

By restricting the API key to localhost, you can be sure that it is used only during development and that your account is not being charged for unauthorized use.