1、跨域请求一些有深度的问题
(1)跨域请求到底会不会发送给后端?
会,跨域请求会发送,只是浏览器不会将返回的数据交给你的js程序。
比如看下面的例子:
package com.example.demo.controller;
import com.example.demo.model.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class MainController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/save")
public User save(int id){
User user= new User();
user.setId(id);
return userRepository.save(user);
}
}
这段后端代码主要保存一个只有一个id字段的用户。
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//实际操作
alert(xhr.responseText);
}
}
}
xhr.open('GET', 'http://localhost:8080/save?id=5', true);
xhr.send();
</script>
</body>
</html>
这段前端代码只有一个脚本,去请求后端这个保存用户的接口,假如这个跨域请求不能请求后端的话,数据是不会添加id为5的用户,但结果数据库中出现了id为5的数据。但是alert没有输出任何信息。
(2)浏览器将跨域请求发送给后端时,会不会自动地将这个域所含有的cookie携带在请求头中?(比如,两个域a.cn、b.cn,我用浏览器登陆b.cn这个网站,然后a.cn这个网站有一段脚本去请求b.cn中的某个接口,这个时候浏览器对于a.cn的这个跨域请求,默认会不会将b.cn中的cookie带入到这个请求中)
答:经过测试Chrome85不会,Edge chromium竟然会携带
后端代码如下:
package com.example.demo.controller;
import com.example.demo.model.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping
public class MainController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/save")
public User save(int id, HttpSession session){
User user= new User();
user.setId(id);
return userRepository.save(user);
}
}
前端代码:
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//实际操作
alert(xhr.responseText);
}
}
}
xhr.withCredentials = true;
xhr.open('GET', 'http://localhost:8080/save?id=8', true);
xhr.send();
</script>
</body>
</html>
这里前端代码重点注意一下 xhr.withCredentials = true;
结果如下
以上图片为Chrome85中的结果:
可以看到用浏览器开的两个标签中请求头的cookie是一样的(sessionid一样),而跨域请求没有请求cookie只有返回cookie。
再看看在Edge中的结果:
三个请求中的cookie一摸一样,不论是否跨域
火狐浏览器的结果与edge一样