登录前后端分离解决跨域(nginx和WebMvcConfigurer)cookic session问题
- 制作登录界面
创建web项目及登录页面
- 创建登录js+ajax
function userLogin() {
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
type: 'post',
xhrFields:{
withCredentials:true
},
data: {
user:111,
password:111
},
dataType: 'text',
success: function (response) {
console.log(response);
setTimeout('location.href=\'index-2.html\'', 3000);
},
error: function (data) {
alert('获取失败');
console.log(data)
}
});}
允许携带cookie
xhrFields:{
withCredentials:true
},
- 后端创建springboot接口(简单接口)
略
- 使用nginx解决跨域问题
nginx安装
http://nginx.org/en/download.html
我的是window系统
直接解压
然后更改配置文件
配置文件是conf的nginx.conf
找不到就搜一下
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8081;
}
error_page 500 502 503 504 /50x.html;
location /page/ {
proxy_pass http://localhost:8080/;
}
}
上面是我的路径
80是nginx路径
proxy_pass http://localhost:8081;
是我的前端路径配好后的访问方式http://localhost
proxy_pass http://localhost:8080/;
这是我的后端路径配好后的访问方式http://localhost/page/
location /page/这里得配成/***/我配成/***访问接口没成功
然后直接点击
启动
如果提前启动了
就在当前路径打开cmd
关闭线程taskkill /IM nginx.exe /F
然后重启start nginx
配好后由于路径都是在localhost:80中自然就没有跨域问题了
在后台创建cookie时需要将cookie路径设置为/不然路径为你的接口路径这样也会导致cookie无法保存。
会导致这种情况
由于session的路径默认为/所以只有session保存成功其他两个失败
username.setPath("/");
pass.setPath("/");
五、下面是我写的简单cookie session代码
Cookie username=new Cookie("user",user);
Cookie pass=new Cookie("password",password);
username.setPath("/");
pass.setPath("/");
response.addCookie(username);
response.addCookie(pass);
if("111".equals(user)&&"111".equals(password)){
HttpSession session=request.getSession();
session.setAttribute("user",user);
if(session.isNew()){
System.out.println("yes");
}else {
System.out.println("no");
}
return "200";
}
// ReturnValue returnValue=new ReturnValue();
return "100";
// }
六、后端允许跨域配置
public class CorsConfig implements WebMvcConfigurer {
// @Bean
// public TomcatContextCustomizer sameSiteCookiesConfig() {
// return context -> {
// final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor();
// cookieProcessor.setSameSiteCookies(SameSiteCookies.NONE.getValue());
// context.setCookieProcessor(cookieProcessor);
// };
// }
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//允许全部请求
.allowedOriginPatterns("*")//允许跨域的请求方路径
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers","Accept")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials","http://localhost:8081")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
}
后台的跨域应该还是需要配置的因为请求过来的地址和后台地址是不一样的
Nginx解决前端跨域