赞
踩
作用是:抛出基础请求方式、基础前缀、请求头信息、参数、超时时间、凭证、后端接口返回数据类型!
-
- //import { baseUrl } from '@/utils/global'
-
- export default {
- method: 'get',
- // 基础url前缀
- baseUrl: process.env.BASE_URL,
- // 请求头信息
- headers: {
- 'Content-Type': 'application/json;charset=UTF-8'
- },
- // 参数
- data: {},
- // 设置超时时间
- timeout: 10000,
- // 携带凭证
- withCredentials: true,
- // 返回数据类型
- responseType: 'json'
- }

作用是:使用请求拦截器和响应拦截器解决下边的问题
- import axios from 'axios'
-
- const request = axios.create({
- baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
- timeout: 5000
- })
-
- // request 请求器
- // 可以自请求发送前对请求做一些处理
- // 比如统一加token,对请求参数统一加密
- request.interceptors.request.use(config => {
- if(config && config.headers){
- config.headers['Content-Type'] = 'application/json;charset=utf-8';
- }
- // config.headers['token'] = user.token; // 设置请求头
- return config
- }, error => {
- return Promise.reject(error)
- });
-
- // response 拦截器
- // 可以在接口响应后统一处理结果
- request.interceptors.response.use(
- response => {
- let res = response.data;
- // 如果是返回的文件
- if (response.config.responseType === 'blob') {
- return res
- }
- // 兼容服务端返回的字符串数据
- if (typeof res === 'string') {
- res = res ? JSON.parse(res) : res
- }
- return res;
- },
- error => {
- console.log('err' + error) // for debug
- return Promise.reject(error)
- }
- )
-
-
- export default request

作用是:这里是放你要请求的接口url、请求方式post/get、传参data最后通过export default方式抛出在页面上调用!
- import axios from "../axios";
-
- export const alldata=(data)=>{
- return axios({
- url:'/article/data',
- method:'post',
- data
- })
- }
-
-
- export default {alldata}
作用是:下载axios!
npm i axios -g
作用是:vue3不支持以 Vue.prototype的方式绑定全局变量,只能以app.config.globalProperties.$http在全局绑定!
图片示例:
- import axios from 'axios'
-
- app.config.globalProperties.$http=axios;
作用是:通过这个服务与另一个网络终端(一般为服务器)进行非直接的连接通过proxy也更改axios
发送请求中,配置请求的根路径!
- // 配置跨域
- const { defineConfig } = require('@vue/cli-service')
- module.exports = defineConfig({
- transpileDependencies: true,
- // lintOnSave:false,
- devServer: {
- port: 8080, // 端口
- proxy: {
- '/api': { // 若请求的前缀不是这个'/api',那请求就不会走代理服务器
- target: 'http://156.61.146.85:8078', //这里写路径
- pathRewrite: { '^/api': '' }, //将所有含/api路径的,去掉/api转发给服务器
- ws: true, //用于支持websocket
- changeOrigin: true //用于控制请求头中的host值
- },
- }
- }
-
- })
-
-

作用是:调接口渲染页面!
图片示例:
- import { reactive,onMounted} from "vue";
- import {alldata} from "@/http/Home/home.js"
- export default {
- name: "app",
- setup(){
- const datas = reactive({
- value:[],
- })
- const methods = {
- requestall(){
- const data={
- pageNum:10,
- pageSize:5,
- articieId:100,
- };
- alldata(data).then(res => {
- datas.value=res
- console.log(res);
- }).catch(err => {
- console.log(err)
- })
- }
- }
- onMounted(()=>{
- methods.requestall()
- })
- return{
- ...methods
- }
- }
- }

图片示例:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。