-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcors-fetch-demo.html
More file actions
73 lines (66 loc) · 2.67 KB
/
cors-fetch-demo.html
File metadata and controls
73 lines (66 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>CORS 联调验证😋</title>
</head>
<body>
<h1>跨域请求示例🌵🌵🌵</h1>
<button id="loginBtn">登录获取token🥳</button>
<br><br>
<button id="fetchBtn">获取所有用户列表😍</button>
<pre id="result"></pre>
<script>
const baseUrl = 'http://localhost:8080/api/user';
// 登录逻辑
document.getElementById('loginBtn').addEventListener('click', async () => {
try {
const res = await fetch(`${baseUrl}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
userId: 10,//改完之后,后端和网页都要重新启动/刷新
password: '123456'
})
});
if (!res.ok) throw new Error(`HTTP错误:${res.status}`);
const data = await res.json();
console.log('登录响应:', data);
if (data.code === 200 && data.data?.accessToken) {
const token = data.data.accessToken;
localStorage.setItem('token', token);
//localStorage是浏览器的本地存储(永久存储,除非手动删除),存进去后刷新页面重启浏览器都还在
document.getElementById('result').textContent = `✅ 登录成功!token已存储到本地`;
} else {
document.getElementById('result').textContent = `❌ 登录失败:${data.message || '未知错误'}`;
}
} catch (err) {
document.getElementById('result').textContent = `❌ 登录出错:${err}`;
}
});
// 获取用户列表逻辑
document.getElementById('fetchBtn').addEventListener('click', async () => {
const token = localStorage.getItem('token');
if (!token) {
document.getElementById('result').textContent = '❌ 先登录!';
return;
}
try {
const res = await fetch(`${baseUrl}/findAll`, {
credentials: 'include',
headers: {
'Access-Token': token // 和拦截器/跨域配置一致
// 手动把Token拼到请求头里
}
});
if (!res.ok) throw new Error(`HTTP错误:${res.status}`);
const data = await res.json();
document.getElementById('result').textContent = JSON.stringify(data, null, 2);
} catch (err) {
document.getElementById('result').textContent = `❌ 请求出错:${err}`;
}
});
</script>
</body>
</html>