Axios 电商商城定制开发是一个基于 promise 的 HTTP 库,电商商城定制开发可以用在浏览器和 node.js 中。
目录
安装
- win+r 电商商城定制开发打开控制台
- cd /项目名
- npm i axios -S
引入
单页面引用
import axios from 'axios'
从node_modules导入的包不需要加./ ../
全局配置
在 main.js 里配置:
- // 导入axios
- import axios from 'axios'
- // 默认请求的基础url(如果axios请求的地址不带域名,自动添加baseURL)(默认请求域名,/当前域名)
- axios.defaults.baseURL = "/"
- // 设置post请求头的content-Type值
- axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
- // 请求超时5000毫秒
- axios.defaults.timeout = 5000;
-
- const app = createApp(App)
- //把axios挂载到vue上,并起一个叫$http的名字
- app.config.globalProperties.$http = axios
- app.use(store).use(router).mount('#app')
代理跨域
不同协议,不同域名,不同端口以及域名和 ip 地址的访问都会产生跨域。这里我们使用代理的方法。
在 vue.config.js 里进行配置:
- const { defineConfig } = require('@vue/cli-service')
- module.exports = defineConfig({
- transpileDependencies: true,
- devServer:{
- proxy:{
- // .php 代理标识符(当请求地址包含.php 字符启用代理)
- ".php":{
- // 本地服务器向 target服务器请求数据
- target:"地址",
- // 允许跨域
- changeOrigin:true,
- }
- }
- }
- })
vue.config.js 文件只要修改就必须重启服务器
使用axios
执行 get 请求
axios.get(url).then(res=>{}).catch(err=>{})
- url 请求的地址
- res 服务器响应的数据
- err 错误信息
get 请求的三种写法
get请求有三种写法,分别是:参数字符串形式写法 ? 、参数对象形式写法 params 、直接使用 axios 方法
- 参数字符串形式写法
this.$http.get("地址?key1=value1&key2=value2").then().catch()
- 参数对象形式写法 params
this.$http.get("地址",{params:{key:value}}).then().catch()
- 直接使用axios方法写get请求
- this.$http({
- url: "地址",
- method: "get",
- params: {
- key: value
- }
- }).then().catch()
这里的 this.$http 与前文中 app.config.globalProperties.$http = axios 保持一致
执行 post 请求
axios.post("url",`date`,config).then().catch()
- url 请求的地址
- date 请求的数据
- config 配置
post 请求的两种写法
在前文全局配置中(axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';)已经配置过 数据格式为url编码 ,所以下文的config可省略不写
- 第一种
- this.$http.post(
- "地址",
- `key=value&key=${value}`,
- { //可省略不写
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded'
- }
- }
- )
- 第二种
- this.$http({
- url:"地址",
- data:`key=value&key=${value}`,
- method:'post',
- headers:{headers:{'Content-Type':'application/x-www-form-urlencoded'}}
- })