How does Vue solve the cross-domain problem of axios request front end

How does Vue solve the cross-domain problem of axios request front end

Preface

Recently, when I was writing a pure front-end vue project, I encountered a problem where access reported 404 when axios requested local resources. This makes me very uncomfortable. After checking the information, it turned out to be a cross-domain problem.

There are many solutions to cross-domain problems in normal development. The most common is the backend modifying the response header. But the front-end can also be solved through a reverse proxy. In order to prevent such mistakes from happening next time, record and summarize them.

So now let's review it and solve it.

1. Why do cross-domain issues occur?

Cross-domain: When a browser requests resources from a web page on one domain name from another domain name, if the domain name, port, or protocol is different, it is cross-domain.

In the front-end and back-end separation mode, the domain names of the front-end and back-end are inconsistent, and cross-domain access problems will occur. The cross-domain problem comes from JavaScript's same-origin policy, which means that only when the protocol + host name + port number (if any) are the same, mutual access is allowed. That is to say, JavaScript can only access and operate resources under its own domain, and cannot access and operate resources under other domains. The cross-domain issue is for JS and ajax. Axios is an encapsulation of ajax technology through Promise, and it also has cross-domain problems.

2. Solution

Here I will use this machine to open two different ports for testing.

Unhandled cross-domain error

There is no cross-domain processing request.

 axios.get('http://localhost:8080/getData')
 .then(res => {
   console.log(res)
 })
 .catch(err => {
   console.error(err); 
 })

Cross-Origin Resource Sharing (CORS)

The front end performs reverse proxy to solve cross-domain problems. The schematic diagram is as follows:

1. The port of the vue project is 8081

2. Open a port 8080 on your computer, and request /getData will return json data.

3. Configure the proxy

1. In vue2.0

Modify the index.js file in the config folder and add the following code to proxyTable:

   proxyTable: {
      '/apis': {
        target: 'http://localhost:8080/', //Domain name to resolve cross-domain interfacesecure:false, //If it is https interface, you need to configure this parameterchangeOrigin: true, //If the interface is cross-domain, you need to configure this parameterpathRewrite: {
          '^/apis': '' // path rewriting}
      },
    },

Then write this in the axios request

 axios.get('apis/getData')
 .then(res => {
   console.log(res)
 })
 .catch(err => {
   console.error(err); 
 })

analyze:

The target is followed by the public part of the URL that needs to be requested, and then /apis is used to proxy this. Finally, some paths are rewritten, and our proxy apis is used as the prefix when requesting.

We can customize this prefix, and proxyTable is an object, so we can configure multiple proxies.

Cross-domain solution

2. In vue3.0

After the vue-cli3 scaffolding is built, there is no vue.config.js file in the project directory and it needs to be created manually

Create a new vue.config.js and configure the following information to solve the problem.

module.exports = {   
    devServer: {
        proxy: {
            '^/api': {
                target: 'http://localhost:8080/', //Interface prefix ws:true, //Proxy websocked
                changeOrigin:true, //The virtual site needs to change the origin
                pathRewrite:{
                    '^/api':''//Rewrite path}
            }
        }
    }
}

summary:

changeOrigin: true : Turn on the proxy: a fake server will be created locally, and then the requested data will be sent and received at the same time, so that the server and the server can interact with each other.

apis is the prefix of the actual interface request, which proxies the public part of our actual interface prefix, that is, protocol + host name + port number

For example, if the request interface is localhost:8080/getData we only need to pass in: getData
Then the public domain name is localhost:8080/ , and we just change the public domain name of the request interface localhost:8080/ to api/ !

Run the project and you can see that the path of the interface request is: localhost:8081/apis/getData

After entering the proxy, the actual request path is: localhost:8080/getData

Final Thoughts

You should still read more official documents during learning. On cross-domain and other configuration issues, the official documents also provide a lot of configuration information, vue cli configuration

To summarize the recent phenomenon: as long as you are not exhausted to death, you will work hard to the death. Come on, everyone.

This is the end of this article about how Vue solves the front-end cross-domain problem of axios requests. For more relevant content about how Vue solves the front-end cross-domain problem of axios requests, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue3 configures axios cross-domain implementation process analysis
  • vue-cli 3.x configures Axios (proxyTable) cross-domain proxy method
  • Solve the cross-domain problem of using axios in vue cli3
  • Vue3.0 axios cross-domain request proxy server configuration method

<<:  mysql update case update field value is not fixed operation

>>:  Docker port mapping and external inaccessibility issues

Recommend

Detailed explanation of nginx optimization in high concurrency scenarios

In daily operation and maintenance work, nginx se...

HTML css js implements Tab page sample code

Copy code The code is as follows: <html xmlns=...

Detailed steps for setting up host Nginx + Docker WordPress Mysql

environment Linux 3.10.0-693.el7.x86_64 Docker ve...

DOCTYPE Document Type Declaration (Must-Read for Web Page Lovers)

DOCTYPE DECLARATION At the top of every page you w...

How to manually deploy war packages through tomcat9 on windows and linux

The results are different in Windows and Linux en...

Introduction to the usage of common XHTML tags

There are many tags in XHTML, but only a few are ...

Vue parent component calls child component function implementation

Vue parent component calls the function of the ch...

Native JS to achieve directory scrolling effects

Here is a text scrolling effect implemented with ...

How to deploy a simple c/c++ program using docker

1. First, create a hello-world.cpp file The progr...

js to achieve waterfall flow layout (infinite loading)

This article example shares the specific code of ...

Implementation of fuzzy query like%% in MySQL

1, %: represents any 0 or more characters. It can...