在Vue中使用axios/全局挂载/默认配置/代理跨域


一、Axios 是什么?

Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送get、post请求。由于vue不再操作操作dom,也就不用导入jQuery,所以axios轻量级库更加适合。

二、Axios使用步骤

安装

npm i axios -S

导入

import axios from 'axios'

注意:从node_modules导入的包不需要加../.../

get请求的几种写法

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

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

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

post请求的几种写法

data格式与config配套的(用哪种格式看接口文档),详见下方代码

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()

三、Axios其他设置

全局挂载

每次使用axios都要再页面引入过于麻烦,所以可以在main.js中进行全局挂载

improt axios from 'axios'

默认配置

//默认请求域名
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

四、通过代理解决跨域问题

vue.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,
		  }
	  }
  }
})

总结

axios可以使数据请求更简单方便,学习使用axios优化自己的项目。

猜你喜欢

转载自blog.csdn.net/TeAmo__/article/details/123352763