【SpringMVC】前后端分离,跨域问题

【SpringMVC】前后端分离,跨域问题_第1张图片

 Access to XMLHttpRequest at 'http://localhost:8080//Users/login.do' from origin 'http://192.168.56.24:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js?1a5c:220          POST http://localhost:8080//Users/login.do net::ERR_FAILED 200
dispatchXhrRequest @ xhr.js?1a5c:220
xhrAdapter @ xhr.js?1a5c:16
dispatchRequest @ dispatchRequest.js?4dc9:58
request @ Axios.js?29fb:109
httpMethod @ Axios.js?29fb:144
wrap @ bind.js?4bea:9
login @ login.vue?01f7:74
click @ login.vue?45a9:76
invokeWithErrorHandling @ vue.runtime.esm.js?c320:2988
invoker @ vue.runtime.esm.js?c320:1786
original_1._wrapper @ vue.runtime.esm.js?c320:7405
:8081/#/login:1 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

解决办法:(两种使用其中一种即可)

!!在配置完之后记得重新启动项目,否则配置可能不生效

后端:

设置允许跨域访问

        response.setHeader("Access-Control-Allow-Origin", "*");//允许所有来源访同
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");//允许访问的方式
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

前端(vue):

设置代理,使用时在目标路径前加上api/就好了

vue.config.js文件里 

【SpringMVC】前后端分离,跨域问题_第2张图片

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    port: 8080, // 端口号
    open: false, //配置是否自动启动浏览器
    https: false,// https:{type:Boolean}是否启用https
    proxy: {
      // 代理
      "/api": {
        target: "http://localhost:8080/",     //要代理访问的路径
        ws: false,// 是否启用websockets
        changeOrigin: true,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite: {
          "^/api": ""//这里理解成用'/api'代替target里面的地址,比如我要调用'http://192.168.0.45:8088/user/getuserlist',直接写'/api/user/getuserlist'即可
        }
      }
    }
  },
})

你可能感兴趣的:(Vue,Java,web,前端,开发语言,vue,java)