spring boot提供了兩種跨域配置方式 1.全局跨域 2.局部跨域 全局跨域 package com.tons.config; import org.springframework.context.annotation.Configuration; import org.springframe ...
spring boot提供了兩種跨域配置方式
1.全局跨域
2.局部跨域
全局跨域
package com.tons.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("/**") // 所有mapping路徑
.allowedOriginPatterns("*") // 所有域 spring-boot 2.4.0及以下使用.allowedOrigins("*")
.allowedMethods("POST","GET","PUT","DELETE","OPTIONS") // 請求方式
.allowedHeaders("*") // 所有方法頭
.maxAge(168000) // 等待間隔時間(時間過了則需再次認證)
.allowCredentials(true); // cookie
}
}
局部跨域。使用CrossOrigin
註解,可修飾類或者方法。
@PostMapping("/log")
@ResponseBody
@CrossOrigin
public String logPost(@RequestBody JSONObject json, HttpSession session) {
String username = json.getString("username");
String password = json.getString("password");
User user = userService.getUserById(username, password);
if (user == null) return RestResult.Error("賬號或者密碼錯誤!");
session.setAttribute("user", user);
return RestResult.OK(UserTokenUtils.encodeUserToKen(user));
}
需要註意的是既是後端開啟跨域並允許攜帶cookie,但是前端每次訪問後端cookie還是會不斷變化。導致HttpSession無法使用
如果想使用HttpSession(後端做無狀態伺服器,就不用HttpSession。轉而使用JWT技術),就需要
1.每次請求攜帶cookie
// 這是ajax請求使用axios.js
axios.defaults.withCredentials = true // axios發送請求帶上cookie,有cookie就有session_id
2.設置反向代理
開發階段 vue-cli
devServer: {
port: 8080,
// 設置代理
proxy: {
// 替換了axios請求中的/api
'/api': {
// 代理地址,這裡設置的地址會代替axios中設置的baseURL
target: 'http://192.168.100.213:8088/',
// 如果介面跨域,需要進行這個參數配置
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
生產階段 ngnix
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
# 配置代理
location /api/ {
proxy_pass http://192.168.100.159:8088/;
proxy_set_header Host 127.0.0.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}