Cross-domain problem of calling third-party such as Baidu map api in vue project

Recently doing a vue project:

First, get the current city information by default, including city name, latitude and longitude, etc.

the way:

1. First introduced in the project directory index.html

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>

The key can be applied through the Baidu Developer Platform

2. Configure the same level as entry in build / webpack.base.conf.js:

3. Restart after configuration is complete, npm run dev

4. If you create a utils.js file in a public file, the code is as follows:

5. Introduce in the file you need to use

import {getCityInfo} from './utils/utils.js'

getCityInfo().then((res) => {

   Specific operation code

}).catch(_ => {});

Demand two: Get the current city latitude and longitude by switching cities, the map needs to be located to the current city (you need to call Baidu api to get the city latitude and longitude interface by city name) http://api.map.baidu.com/geocoder/v2/?address = Beijing & output = json & ak = Your key

Way: (The best way is through jsonp, which will be described in detail below)

Before using jsonp, I tried many other methods, all of which failed. I used the method of adding a proxyTable proxy under config / index.js, but this method can only be effective in the development environment. The domain problem still exists, and the debug interface for the development environment is ok as follows:

The request method in the vue page is as follows:

       ps: The requested URL can be as follows

        axios ({
          url: "/ v2 /? address = Chengdu & output = json & ak = your key",   
        }). then (res => {
           specific operation
        })

Next, talk about the simple, direct and violent way:

Direct npm install vue-jsonp --save install dependencies

Then introduce in main.js

Use in vue page:

Perfect solution to cross-domain problems!

H-L
Published 8 original articles · Likes5 · Visits 40,000+

Guess you like

Origin blog.csdn.net/helenwei2017/article/details/89668531