封装的目的在于复用。
封装的目的在于把公共部分封装。
好了,相信你能理解上面两句话
下面我就针对axios的get请求和post请求进行封装啦!我用TypeScript写的,其实我写的更像JS!
import {Injectable } from '@angular/core';import axios from 'axios';@Injectable({providedIn: 'root'})export class TestService {//公共的baseURL,一般是服务器ip和端口baseURL:string = "http://localhost:3000/api"constructor() {}//无参数get方法getDataNullParams(url:string){return axios({url:this.baseURL + url,method:'get'})}//有参数get方法getDataWithParams(url:string,params:any){return axios({url:this.baseURL + url,method:'get',params:params})}//post方法postData(url:string,params:any){return axios({url:this.baseURL+url,method:'post',data:params})}}
调用的话就很简单咯,无论是post还是 get,只要传入url和参数即可。
下面是调用的示例:
postDataEvent(){this.server.postData('/addUser',{username:'hhr',password:'aini',power:1}).then((res)=>{console.log(res);})}
补充,有时候前端跨域很烦,补充vue的跨域解决方案
:
1.在根目录生成vue.config.js
2.vue.config.js文件代码:
module.exports = {assetsDir: 'assets', //静态资源目录(js, css, img)lintOnSave: false, //是否开启eslintdevServer: {open: true, //是否自动弹出浏览器页面host: "localhost", port: '8080', https: false, //是否使用https协议hotOnly: false, //是否开启热更新proxy: {'/api': {target: 'http://47.106.185.34:8182', //API服务器baseURLchangeOrigin: true,pathRewrite: {'^/api': ''}}}},publicPath: ''}
3.发送请求的时候加上/api
则匹配成功,转向配置的跨域的目的地址。例子如下:
this.server.postData('/api/addUser',{// ==>代理后:http://47.106.185.34:8182/addUserusername:'hhr',password:'aini',power:1}).then((res) => {console.log(res);}).catch( err => {console.log(err);})}
补充另外几个put、patch、delete的使用注意点:
import axios from "axios"/*** 使用post、patch、put方法传递参数注意:* data:方法请求的参数会放到请求体body里面,后台接收的是json的格式,可传递特殊字符* params(同get方法):方法请求的参数会放到url字符串里面,后台接收的是字符串键值的形式,不可传递特殊字符*/export default {get(url,params){return axios({url:url,method:'get',params:params})},post(url,params){return axios({url:url,method:'post',params:params})},/**post(url,params){return axios({url:url,method:'post',data:params})},*/put(url,params){return axios({url:url,method:'put',params:params})},patch(url,params){return axios({url:url,method:'patch',params:params})},delete(url,params){return axios({url:url,method:'delete',params:params})}}
好了,希望本文对你有帮助,我也是理解了很多次才能写出跨域了^^
如果觉得《axios常用请求的封装(get post等方法的封装vue的跨域解决方案)》对你有帮助,请点赞、收藏,并留下你的观点哦!