How to solve the cross-domain, the front-end cross-domain is no longer worrying, it is simple and fast, only four steps

The personal test is successful, everyone can give me more guidance, and personally accept all kinds of criticism and corrections!

Step 1: Add the following code to the vue.config.js file:

(If there is no vue.config.js file, create a new one. The file name must be correct, otherwise it cannot be read)
const {
    
     defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
    
    
  transpileDependencies: true,
 //主要代码******start
		  devServer: {
    
    
		    **proxy: {
    
    
		      "/api": {
    
    
		        target: "http://116.176.33.120:58081/prod-api/rygs", 
		        ws: true, 
		        changeOrigin: true,
		        pathRewrite: {
    
    
		          "^/api": ""
		        },
		      },
		    },
//主要代码*********end
  },
});

Step 2: Install and configure axios

1. Install axios

npm install axios -g

or

npm i axios -g

2. Introduce axios globally

Introduce the following code in main.js
		main.js文件肯定有,不需要新建哦,注意把axios挂载到Vue原型上时前面的   $    符号。
import axios from ”axios“
Vue.prototype.$axios=axios
import axios from ”axios“
Vue.prototype.$axios=axios

third step

Enter the following code where you need to send a request:

 this.$axios
      .post("api/输入请求路径", { 请求参数: 请求参数值 })//这里的api/必须加
      .then(res => { console.log("res", res))
      .catch(err => console.log("err", err));

the fourth step

important step

		你成功了!!!

If you have any questions, please leave a message

There is also a second solution, just one step, call the back-end brother, say cross-domain, deal with it, drink tea and wait

Guess you like

Origin blog.csdn.net/m0_71585401/article/details/129852641