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);
});
},
效果
第二种方法给后端加一个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
效果