crm开发定制Vue学习(七)——引入Axios

前言

推荐使用Axios用于Ajax调用。crm开发定制本文介绍如何在Vuecrm开发定制项目中引入Axios。

crm开发定制准备服务端程序

crm开发定制本服务端程序仅用来测试,crm开发定制如果读者有其他restcrm开发定制接口用于测试可跳过此节。

我通过Eclipse。首先新建maven

选择webapp那一项

crm开发定制填写必要信息便可完成

修改pom.xml文件,主要增加对spring-boot和spring-mvc的依赖。前几行注释掉的地方是我的项目信息,读者可以改成自己的。

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <!-- 改成你的项目信息
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.sadoshi.springboot</groupId>
  6. <artifactId>SpringbootTest</artifactId>
  7. <packaging>war</packaging>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <name>SpringbootTest Maven Webapp</name>
  10. <url>http://maven.apache.org</url>
  11. -->
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>2.6.2</version>
  16. <relativePath />
  17. </parent>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-web</artifactId>
  22. </dependency>
  23. </dependencies>
  24. <build>
  25. <pluginManagement>
  26. <plugins>
  27. <plugin>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-maven-plugin</artifactId>
  30. </plugin>
  31. </plugins>
  32. </pluginManagement>
  33. </build>
  34. </project>

在src/main文件夹下新增目录java,新建主类App.java

  1. package com.sadoshi.springboottest;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import com.sadoshi.springboottest.App;
  5. @SpringBootApplication
  6. public class App {
  7. public static void main(String[] args) {
  8. SpringApplication.run(App.class, args);
  9. }
  10. }

新建一个controller处理类HelloController.java,作为rest接口:

  1. package com.sadoshi.springbootABC;
  2. import org.springframework.web.bind.annotation.PostMapping;
  3. import org.springframework.web.bind.annotation.RequestBody;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. @RequestMapping("/hello")
  8. public class HelloController {
  9. @RequestMapping("")
  10. public String test() {
  11. return "test HelloController";
  12. }
  13. @PostMapping("/name")
  14. public String name(@RequestBody String name) {
  15. return "hello " + name;
  16. }
  17. }

启动App类,然后浏览器调用,如果出现以下页面则表示成功:

新建

和前面一样,我们先新建Vue项目并安装依赖:

  1. vue create axios1
  2. cd axios1
  3. npm install

谨记,项目名不要设成“axios”,否则安装axios依赖时,会由于同名导致安装依赖失败。

接着安装axios依赖

npm install axios --save

在main.js中引入axios,并添加到全局环境,这样就不用在每个需要用到axios的组件里都import引入。

  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios'
  4. Vue.prototype.$axios = axios
  5. Vue.config.productionTip = false
  6. new Vue({
  7. render: h => h(App),
  8. }).$mount('#app')

简化App.vue,去掉多余的信息

  1. <template>
  2. <div id="app">
  3. <HelloWorld/>
  4. </div>
  5. </template>
  6. <script>
  7. import HelloWorld from './components/HelloWorld.vue'
  8. export default {
  9. name: 'App',
  10. components: {
  11. HelloWorld
  12. }
  13. }
  14. </script>
  15. <style>
  16. </style>

HelloWorld.vue修改为:

  1. <template>
  2. <div class="hello">
  3. <button @click="onHello">测试</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'HelloWorld',
  9. data() {
  10. return {
  11. name: '',
  12. }
  13. },
  14. methods: {
  15. onHello(){
  16. this.$axios.get("/hello").then(res => {
  17. console.log(res);
  18. })
  19. }
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

启动项目,看到以下界面:

点击测试按钮,调用后端接口http://localhost:8080/hello,我们点f12查看调试信息:

看到报错信息,意思是跨域。显然我们在localhost:8081调用localhost:8080属于跨域。那我们要怎么处理呢?

处理跨域问题

主要是通过代理方式解决。通常项目中,我们前端调用会增加一个前缀,通常是“api”,修改main.js:

  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios'
  4. Vue.prototype.$axios = axios
  5. Vue.config.productionTip = false
  6. axios.defaults.baseURL = '/api'
  7. new Vue({
  8. render: h => h(App),
  9. }).$mount('#app')

在第8行添加内容之后,对于相对路径,后面axios调用都会加上api前缀(绝对路径则不变)。接着我们设置代理,在项目根路径下创建vue.config.js文件(与src、package.json目录同级)。

  1. module.exports = {
  2. devServer: {
  3. proxy: {
  4. '/api': {
  5. target: 'http://localhost:8080/',
  6. // 允许跨域
  7. changeOrigin: true,
  8. pathRewrite: {
  9. '^/api': ''
  10. }
  11. }
  12. }
  13. }
  14. }

上面的意思是,对于前缀api的调用,请求时替换成调用。这里记得一定要加上http这个前缀

修改HelloWorld.vue,axios调用改为使用相对路径

  1. <template>
  2. <div class="hello">
  3. <button @click="onHello">测试</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'HelloWorld',
  9. data() {
  10. return {
  11. name: '',
  12. }
  13. },
  14. methods: {
  15. onHello(){
  16. this.$axios.get("/hello").then(res => {
  17. console.log(res);
  18. })
  19. }
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

重新运行项目,然后点击按钮,可以看到调用成功了

不过上面返回的信息量有点大,如果在业务代码中处理各种返回信息会显得很繁琐(例如返回200时怎么做,返回400时怎么做,返回500时怎么样做,尤其是一些嵌套调用。所以通常会对返回信息进行封装,在业务层仅进行数据处理就好了。

封装axios调用

封装axios通常使用axios拦截器实现。不过封装的情况和rest接口返回信息,以及读者的应用要如何处理异常情况有关,这里展示一下简单的封装,在src目录下新建utils目录,在src/utils目录下新建request.js:

  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message } from 'element-ui'
  3. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  4. // 创建axios实例
  5. const service = axios.create({
  6. // axios中请求配置有baseURL选项,表示请求URL公共部分
  7. baseURL: '/api',
  8. // 超时
  9. timeout: 10000
  10. })
  11. // request拦截器
  12. service.interceptors.request.use(config => {
  13. return config
  14. }, error => {
  15. console.log(error)
  16. Promise.reject(error)
  17. })
  18. // 响应拦截器
  19. service.interceptors.response.use(res => {
  20. // 未设置状态码则默认成功状态
  21. const code = res.data.code || 200;
  22. // 获取错误信息
  23. const message = res.data.msg
  24. if (code === 401) {
  25. MessageBox.confirm(
  26. '登录状态已过期,您可以继续留在该页面,或者重新登录',
  27. '系统提示',
  28. {
  29. confirmButtonText: '重新登录',
  30. cancelButtonText: '取消',
  31. type: 'warning'
  32. }
  33. ).then(() => {
  34. // store.dispatch('LogOut').then(() => {
  35. // location.reload() // 为了重新实例化vue-router对象 避免bug
  36. // })
  37. })
  38. } else if (code === 500) {
  39. Message({
  40. message: message,
  41. type: 'error'
  42. })
  43. return Promise.reject(new Error(message))
  44. } else if (code !== 200) {
  45. Notification.error({
  46. title: message
  47. })
  48. return Promise.reject('error')
  49. } else {
  50. return res.data
  51. }
  52. },
  53. error => {
  54. console.log('err' + error)
  55. Message({
  56. message: error.message,
  57. type: 'error',
  58. duration: 5 * 1000
  59. })
  60. return Promise.reject(error)
  61. }
  62. )
  63. export default service

上面的代码引入了element ui这个开源组件,主要是异常处理时前端如何提示。读者也可以按照自己的需要做对应的提示,也可以把element ui相关的那几行注释掉。由于第8行已经设置了baseURL,所以main.js第8行“axios.defaults.baseURL = '/api'”这句可以删掉。

通常实际项目对后台的调用都是定义在api目录里面,例如我们在src下新建目录api,目录下新建hello.js:

  1. import request from '../utils/request'
  2. export function hello() {
  3. return request({
  4. url: '/hello',
  5. method: 'get'
  6. })
  7. }
  8. export function sayHello(data) {
  9. return request({
  10. url: '/hello/name',
  11. method: 'post',
  12. data: data
  13. })
  14. }

之后修改下HelloWorld.vue

  1. <template>
  2. <div class="hello">
  3. <button @click="onHello">测试</button>
  4. 名字:<input v-model="name" />
  5. <button @click="onName">发送</button>
  6. </div>
  7. </template>
  8. <script>
  9. import { hello, sayHello } from '@/api/hello'
  10. export default {
  11. name: 'HelloWorld',
  12. data() {
  13. return {
  14. name: '',
  15. }
  16. },
  17. methods: {
  18. onHello(){
  19. hello().then(res => {
  20. console.log(res)
  21. })
  22. },
  23. onName(){
  24. sayHello(this.name).then(res => {
  25. console.log(res)
  26. })
  27. }
  28. }
  29. }
  30. </script>
  31. <style scoped>
  32. </style>

启动项目后,分别测试两个按钮的效果即可。对于成功的调用,仅返回数据,就不用业务层处理繁琐的返回信息。

小结:

axios的使用很简单,大多数情况下只要项目封装好之后,直接调用封装的request即可,一般不必再写axios。

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发