current position:Home>How to configure Vue in Vue project config. JS to solve cross domain problems

How to configure Vue in Vue project config. JS to solve cross domain problems

2022-04-29 07:22:09Invincible beautiful girl 2000

Recently written vue When the project requests a custom interface , There's a cross domain problem . The error code is as follows :

Access to XMLHttpRequest at 'http://localhost:5001/index' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Checked a lot, many solutions are useless .
here , The way I used is to configure vue.config.js file , If there is no such document , Create a new one under the root directory of the project .

principle :
1、 Send the domain name to the local server (localhost:8080)
2、 Then the local server requests the real server
3、 The request sent by the server , There is no cross domain problem

Here are vue.config.js Detailed configuration of :

//  Export module 
module.exports = {
    
  devServer: {
    
    proxy: {
     //  Configure cross domain 
      '/api': {
    
        target: `http://127.0.0.1:5001/`,   // Custom request background interface 
        changeOrigin: true, //  Allow cross-domain 
        pathRewrite: {
    
          '^/api': '' //  Rewrite request 
        }
      }
    }
  }
}

Be careful : modify vue.config.js after , Need to restart service
And then use axios For the request :

// http://127.0.0.1:5001/index Is a custom interface 
//  To solve cross domain problems , Configured with vue.config.js file 
//this.$axios.get('http://127.0.0.1:5001/index').then(
this.$axios.get('api/index').then(
	(res) => {
    
		console.log(res.data)
	},
	(err) => {
    
		console.log(err)
	}
)

there api/ Instead of http://127.0.0.1:5001/.

copyright notice
author[Invincible beautiful girl 2000],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290424394867.html

Random recommended