1、vue
在vue.config 文件里面配置 如果没有 vue.config文件就新建一个
module.exports = defineConfig(
devServer: {
open: true,
proxy: {
"/api": {
target: "http://localhost:9092/",
ws: true,
changOrigin: true,
pathRewrite: {
"^/api": ""
}
}
}
}
})
2、java 后台配置
/**
*添加全局配置,则需要添加一个配置类 :
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
3、nginx
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
/**
参数说明
1. Access-Control-Allow-Origin
服务器默认是不被允许跨域的。给Nginx服务器配置`Access-Control-Allow-Origin *`后,表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。
2. Access-Control-Allow-Headers 是为了防止出现以下错误:
复制
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
1.
这个错误表示当前请求Content-Type的值不被支持。其实是我们发起了"application/json"的类型请求导致的。这里涉及到一个概念:预检请求(preflight request),请看下面"预检请求"的介绍。
3. Access-Control-Allow-Methods 是为了防止出现以下错误:
复制
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
1.
4. 给OPTIONS 添加 204的返回,是为了处理在发送POST请求时Nginx依然拒绝访问的错误
发送"预检请求"时,需要用到方法 OPTIONS ,所以服务器需要允许该方法。
*/
更多推荐
Vue 跨域问题 的几种解决办法 (No ‘Access-Control-Allow-Origin‘ header is present on the requ
发布评论