Use axios/global mount/default configuration/proxy cross-domain in Vue


1. What is Axios?

Axios is a promise-based HTTP library. Simply put, it can send get and post requests. Since vue no longer operates dom, it does not need to import jQuery, so axios lightweight library is more suitable.

2. Axios usage steps

Install

npm i axios -S

import

import axios from 'axios'

Note: Packages imported from node_modules do not need to add ../.../

Several ways of writing get request

axios.get(url).then().catch()

axios.get(url,{params:{查询参数}}).then().catch()

axios({
	url:请求地址,
	method:"get",
	params:请求参数
}).then().catch()

Several ways of writing post requests

The data format is matched with config ( see the interface document for which format to use ), see the code below for details

axios.post(url,data,config).then().catch()

//data格式与config配套的(用哪种格式看接口文档)
axios.post(
	"/index_login.php",
	"name=mewow&age=18",
	{headers:{'Content-Type':'application/x-www-form-urlencoded'}}
	)
			
axios.post("/index_login.php",
	{name:"mewow",age=18},
	{headers:{'Content-Type':'application/json'}}
	)

axios({
    url:请求地址,
    method:"post",
    data:请求参数,
    headers:{请求头信息}
}).then().catch()

3. Other settings of Axios

global mount

It is too troublesome to introduce the page every time you use axios, so you can mount it globally in main.js

improt axios from 'axios'

default allocation

//默认请求域名
axios.defaults.baseURL = "/"
//post请求默认请求头
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
//默认请求超时
axios.defaults.timeout = 5000;
//挂载
const app = createApp(App);
app.config.globalProperties.$http = axios;
app.use(store).use(router).mount('#app')
//$http自定义名称 建议$http

4. Solve cross-domain problems through proxies

view.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer:{
	  proxy:{
		  // .php 代理标识符(当请求地址包含.php 字符启用代理)
		  ".php":{
			  // 本地服务器向 target服务器请求数据
			  target:"https://www.520mg.com/",
			  // 允许跨域
			  changeOrigin:true,
		  }
	  }
  }
})

Summarize

Axios can make data requests easier and more convenient, learn to use axios to optimize your own projects.

Guess you like

Origin blog.csdn.net/TeAmo__/article/details/123352763