前端配置

前端框架基于https://panjiachen.github.io/vue-admin-template二次开发, 是应用封装的Axios 的service

封装代码 src/utils/request.js

  1. import axios from 'axios'
  2. import { MessageBox, Message } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. // create an axios instance
  6. const service = axios.create({
  7. baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  8. // withCredentials: true, // send cookies when cross-domain requests
  9. timeout: 5000 // request timeout
  10. })
  11. // request interceptor
  12. service.interceptors.request.use(
  13. config => {
  14. // do something before request is sent
  15. if (store.getters.token) {
  16. // let each request carry token
  17. // ['X-Token'] is a custom headers key
  18. // please modify it according to the actual situation
  19. config.headers['X-Token'] = getToken()
  20. }
  21. return config
  22. },
  23. error => {
  24. // do something with request error
  25. console.log(error) // for debug
  26. return Promise.reject(error)
  27. }
  28. )
  29. // response interceptor
  30. service.interceptors.response.use(
  31. /**
  32. * If you want to get http information such as headers or status
  33. * Please return response => response
  34. */
  35. /**
  36. * Determine the request status by custom code
  37. * Here is just an example
  38. * You can also judge the status by HTTP Status Code
  39. */
  40. response => {
  41. const res = response.data
  42. // if the custom code is not 20000, it is judged as an error.
  43. if (res.code !== 20000) {
  44. Message({
  45. message: res.message || 'Error',
  46. type: 'error',
  47. duration: 5 * 1000
  48. })
  49. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  50. if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  51. // to re-login
  52. MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  53. confirmButtonText: 'Re-Login',
  54. cancelButtonText: 'Cancel',
  55. type: 'warning'
  56. }).then(() => {
  57. store.dispatch('user/resetToken').then(() => {
  58. location.reload()
  59. })
  60. })
  61. }
  62. return Promise.reject(new Error(res.message || 'Error'))
  63. } else {
  64. return res
  65. }
  66. },
  67. error => {
  68. console.log('err' + error) // for debug
  69. Message({
  70. message: error.message,
  71. type: 'error',
  72. duration: 5 * 1000
  73. })
  74. return Promise.reject(error)
  75. }
  76. )
  77. export default service

在调用该方法时, 直接使用封装好的service (axios instance) 即可:

  1. import service from '@/utils/request'
  2. export default {
  3. test() {
  4. return service({ // Promise
  5. // 方位后台url,这里写死
  6. url:'http://localhost:8080/dev-api/getMockPersonInfo',
  7. method: 'post',
  8. //post提交的payload
  9. data: {
  10. "name": "王静飞",
  11. }
  12. })
  13. }
  14. }

跨域无法访问

这里我们前端的url地址时: http://localhost:9530/
此时, 由于后端和前端的端口号不一样, 存在跨域无法访问状态.

修改后端

后端的对应 url:’http://localhost:8080/dev-api/getMockPersonInfo’的controller为

  1. @Controller
  2. //修改部分, 可以处理所有
  3. @CrossOrigin(origins = "*", maxAge = 3600)
  4. @RequestMapping("/dev-api")
  5. public class MockHandler {
  6. @Autowired
  7. PersonInfoService PIService;
  8. @ResponseBody
  9. @RequestMapping(value = "getMockPersonInfo")
  10. public RetBody getPersonInfo(PersonInfoVO PI, NeedPage needPage) {
  11. if (HttpHolder.needPage()) {
  12. PageHelper.startPage(needPage.getCurpage(), needPage.getPagesize(), HttpHolder.needPage());
  13. }
  14. List<PersonInfo> personList = PIService.getMapper().query(PI);
  15. return RetBody.gridData(personList);
  16. }
  17. }

如果Spring版本为4.2+,则可以在Controller类或其方法上加@CrossOrigin注解,来使之支持跨域:

其中origins为@CrossOrigin的默认参数,即跨域来源,*表示任何来源,也可以是其它域名。比如如下形式:

@CrossOrigin(“http://localhost:4200“)
@CrossOrigin(origins={“http://localhost:4200“, “http://localhost:4242"})
@CrossOrigin(origins=”http://localhost:4200",maxAge=3600)

参考链接:https://blog.csdn.net/White_Idiot/article/details/80657796