Home > Web Front-end > Vue.js > How vue.js solves cross-domain problems

How vue.js solves cross-domain problems

王林
Release: 2023-01-13 00:45:47
Original
5339 people have browsed it

Vue.js method to solve cross-domain problems: 1. Enter the vue project root directory; 2. Find the vue.config.js file and open it with an editor; 3. Set cross-domain in proxy .

How vue.js solves cross-domain problems

The operating environment of this article: windows10 system, vue 2.5.2, thinkpad t480 computer.

To implement cross-domain in vue development, you need to first enter the vue project root directory, find the vue.config.js file, and then set the cross-domain in the proxy:

Tips: If you cannot find it Go to the vue.config.js file and create one yourself.

devServer: {
    proxy: {  //配置跨域
      '/api': {
        target: 'http://121.121.67.254:8185/',  //这里后台的地址模拟的;应该填写你们真实的后台接口
        changOrigin: true,  //允许跨域
        pathRewrite: {
          /* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
            实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
           */
          '^/api': '' 
        }
      },
    }
  },
Copy after login

The principle of using proxy in vue for cross-domain is: send the domain name to the local server (start the service of the vue project, loclahost:8080), and then the local server requests the real server.

The following are the steps I took to implement cross-domain development in the vue project:

1. Set the address to be accessed in the proxy, and rewrite the /api empty string, because we The actual requested address does not include /api. This rewriting is very important!!!

How vue.js solves cross-domain problems

#2. When creating an axios instance, set the baseURL to /api. At this time Our cross-domain has been completed.

How vue.js solves cross-domain problems

3. If the real address of the request is: http://121.121.67.254:8185/core/getdata/userInfo, but we will see it on the browser Like this: http://localhost:8080/api/core/getData/userInfo, there is an extra /api, but it does not affect our request for data.

How vue.js solves cross-domain problems

Recommended learning: php training

The above is the detailed content of How vue.js solves cross-domain problems. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template