Vue addresses front-end cross-domain issues with AXIOS requests

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Recently, while writing a pure front-end VUE project, I encountered a problem with axios requesting a native resource and accessing the 404 message. It makes me sick. The query 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 modify response header. But the front end can also be solved by reverse proxy. To prevent this from happening again, take notes and summarize.

So now let’s go over it and get it over with.

First, why do cross-domain problems occur?

Cross-domain: When a browser requests resources of another domain name from a web page of a domain name, the domain name, port, or protocol is cross-domain.

When the front and back ends are separated, domain names of the front and back ends are inconsistent, which causes cross-domain access problems. The cross-domain problem stems from JavaScript’s same-origin policy, which allows mutual access if only the protocol, host name, and port number (if any) are the same. This means that JavaScript can only access and manipulate resources in its own domain, not resources in other domains. Cross-domain issues are specific to JS and Ajax. Axios, which encapsulates Ajax technology through Promise, also has cross-domain problems.

Second, solutions

Here I use this machine to open two different ports to test.

Failed to handle cross – domain error

Not doing cross-domain processing requests is like this

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

Cross-domain Resource Sharing (CORS)

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

  1. Port for the VUE project is 8081

  1. If you open port 8080 on your computer, request /getData will return json data.

  2. Configure the agent

1. In the vue2.0

Add proxyTable to index.js file in config folder:

   proxyTable: {
      '/apis': {
        target: 'http://localhost:8080/'.// The name of the interface to be resolved across domains
        secure:false.// If the interface is HTTPS, you need to set this parameter
        changeOrigin: true.// This parameter is required if the interface is cross-domain
        pathRewrite: {
          '^/apis': ' '  // Path overwrite}}},Copy the code

And then in the request axios says this

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

Target = /apis > target = /apis > target = /apis > /apis This prefix can be customized. ProxyTable is an object, so we can have multiple proxies.

Cross-domain solutions

2. In the vue3.0

After the scaffolding of VUE-cli3 is built, the vue.config.js file does not exist in the project directory and needs to be created manually

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

module.exports = {   
    devServer: {
        proxy: {
            '^/api': {
                target: 'http://localhost:8080/'.// The prefix of the interface
                ws:true./ / agent websocked
                changeOrigin:true.// Virtual sites need to manage origin
                pathRewrite:{
                    '^/api':' '// Rewrite the path
                }
            }
        }
    }
}
Copy the code

Summary:

ChangeOrigin: true: enable proxy: a fake server is created locally and sends the requested data and receives the requested data at the same time. In this way, the server and the server can exchange data.

Apis are the prefix of the actual interface request, proxies for the common part of our actual interface prefix, which is protocol + host name + port number

For example, if the request interface is localhost:8080/getData we just pass in: getData and the public domain name is localhost:8080/, we’re asking for the public domain name of the interface localhost:8080/ API /!

The project to run interface can see the path of the request is: localhost: 8081 / apis/getData and after into agent, the actual request path is: localhost: 8080 / getData

Write in the last

In learning, we still need to read more official documents. In terms of cross-domain configuration, the official documents also provide a lot of configuration information, such as Vue CLI configuration

Let me summarize the recent phenomenon: as long as you don’t die, you die. Come on, guys.

Welcome to comment on articles and technical exchanges.