zoukankan      html  css  js  c++  java
  • Vue+SpringBoot前后端分离中的跨域问题

    在前后端分离开发中,需要前端调用后端api并进行内容显示,如果前后端开发都在一台主机上,则会由于浏览器的同源策略限制,出现跨域问题(协议、域名、端口号不同等),导致不能正常调用api接口,给开发带来不便。

    封装api请求

     1 import axios from 'axios'
     2 
     3 //axios.create创建一个axios实例,并对该实例编写配置,后续所有通过实例发送的请求都受当前配置约束
     4 const $http = axios.create({
     5     baseURL: '',
     6     timeout: 1000,
     7     //headers: {'X-Custom-Header': 'foobar'}
     8 });
     9 
    10 // 添加请求拦截器
    11 $http.interceptors.request.use(function (config) {
    12     // 在发送请求之前做些什么
    13     return config;
    14 }, function (error) {
    15     // 对请求错误做些什么
    16     return Promise.reject(error);
    17 });
    18 
    19 // 添加响应拦截器
    20 $http.interceptors.response.use(function (response) {
    21     // 对响应数据做点什么
    22     return response.data;   //返回响应数据的data部分
    23 }, function (error) {
    24     // 对响应错误做点什么
    25     return Promise.reject(error);
    26 });
    27 
    28 export default $http

    api调用函数

    1 export const getCourses = () => {
    2     return $http.get('http://localhost:8080/teacher/courses')
    3 }

    在本例中,前端使用8081端口号,后端使用8080端口号,前端通过调用api请求数据失败

    postman测试此api接口正常

    如何解决同源问题?

    1、在vue根目录下新建vue.config.js文件并进行配置

    vue.config.js文件

     1 module.exports = {
     2     devServer: {
     3         host: 'localhost',        //主机号
     4         port: 8081,               //端口号
     5         open: true,               //自动打开浏览器
     6         proxy: {
     7             '/api': {
     8                 target: 'http://localhost:8080/',       //接口域名
     9                 changeOrigin: true,                     //是否跨域
    10                 ws: true,                               //是否代理 websockets
    11                 secure: true,                           //是否https接口
    12                 pathRewrite: {                          //路径重置
    13                     '^/api': '/'
    14                 }
    15             }
    16         }
    17     }
    18 };

    2、修改api请求

    api调用函数

    1 export const getCourses = () => {
    2     return $http.get('/api/teacher/courses')
    3 }

    在这里,因为vue.config.js配置了接口域名,所以此处url只需要写余下来的部分

    url完全体

    1 http://localhost:8080/teacher/courses

    但是这里因为运用到代理,所以在余下的部分(即'/teacher/courses')前加上'/api',组成'/api/teacher/courses'

    此时跨域问题解决,前端可以从后端接口拿到数据并显示

    问题解决!

    吾生也有涯,而知也无涯
  • 相关阅读:
    透过书本了解HTML5
    Seam性能讨论
    Maven依赖管理
    Tapestry
    为HTML5的未来制定学习计划
    后缀数组
    HDU 1042(大数)
    教你理解复杂的C/C++声明
    编程修养
    平衡二叉树
  • 原文地址:https://www.cnblogs.com/huskysir/p/15130380.html
Copyright © 2011-2022 走看看