Vue+SpringBoot+Axios的跨域问题

Vue+SpringBoot+Axios的跨域问题

第一种方法前端解决

第一步在vue.config.js中编辑devServer

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    proxy: { 
      '/api': {
        target: 'http://localhost:8081/', //填写请求的目标地址
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': '' //请求的时候使用这个api就可以
        }
      }
    }
  }
})

如果没有vue.config.js文件则找config下面的index.js配置

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {  //代理地址
        target: 'http://localhost:8001',  //需要代理的地址, 实际生产环境需要访问的地址
        changeOrigin: true,  //是否跨域
        secure: false,
        pathRewrite: {
          '^/api': ''   //本身的接口地址没有 '/api' 这种通用前缀,所以要rewrite,如果本身有则去掉
        }
      }
    },

第二步编辑main.js

import axios from 'axios'
axios.defaults.baseURL = '/api'

第三步发起请求

  mounted() {
    axios.get('/users/test')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  },

效果

image-20230414212257869

第二种方法给后端加一个config

package com.zhiwei.sbappaf.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//解决跨域问题的配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

生产环境(nginx)部署

修改nginx.conf

server {
        listen       82;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html/dist/;
            index  index.html index.htm;
        }

        location /api {
            #rewrite ^/api?(.*)$ $1 break;
            proxy_pass http://localhost:8081;
        }

其实nginx配置对应的就是开发环境中的

  devServer: {
    proxy: { 
      '/api': {
        target: 'http://localhost:8081/', //填写请求的目标地址
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': '' //请求的时候使用这个api就可以
        }
      }
    }
  }

这里的 proxy对应的就是nginx中的proxy_pass

效果

image-20230415141539886

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值