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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539836.html
標籤:其他
