因为现在都是用第三方插件啥的原生得忘得差不多了、在登录这走了很多弯路,所以写了这一篇原生js+(ajax、fetch)实现登录跳转的文章,希望对你有帮助
1. 创建 ajax.js
1、创建网络请求的AJAX对象(使用XMLHttpRequest)
2、监听XMLHttpRequest对象状态的变化,或者监听onload事件(请求完成时触发);
3、配置网络请求(通过open方法), open方法可以传入两个参数;
参数一: method(请求的方式: get, post …)
参数二: url(请求的地址)
4、发送send网络请求;
// 封装 ajax
function ajax(options) {
let params = formsParams(options.data);
//创建对象
const xhr = new XMLHttpRequest()
// 连接
if (options.type == "GET") {
// 配置网络请求(通过open方法), open方法可以传入两个参数
xhr.open(options.type, options.url + "?" + params, options.async);
xhr.send(null)
} else if (options.type == "POST") {
xhr.open(options.type, options.url, options.async);
if (!options.headers) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} else {
xhr.setRequestHeader("Authorization", options.headers.Authorization)
}
xhr.send(params);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
options.success(xhr.responseText);
}
}
function formsParams(data) {
let arr = [];
for (let prop in data) {
arr.push(prop + "=" + data[prop]);
}
return arr.join("&");
}
}
2. 在登录页中使用封装好的 ajax 和 fetch 实现登录跳转用户页面
请求成功需要把sessionToken保存到 localStorage中,
如: localStorage.setItem('userinfo', res.data.sessionToken),
因为除了登录所有接口请求头request headers中都得有Authorization:后端返回的token
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页</title>
</head>
<body>
<input type="text" id="phone" placeholder="请输入账号">
<input type="text" id="password" placeholder="请输入密码">
<button id="login">登录</button>
<script src="./ajax.js"></script>
<script>
login.onclick = function () {
fetch("你的接口地址", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `phone=${phone.value}&password=${password.value}`
}).then(res => res.json())
.then(res => {
localStorage.setItem('userinfo', res.data.sessionToken)
open('./user.html')
})
// ajax({
// url: "你的接口地址", // url---->地址
// type: "POST", // type ---> 请求方式
// async: true, // async----> 同步:false,异步:true
// data: { //传入信息
// phone: phone.value,
// password: password.value
// },
// success: function (data) { //返回接受信息
// const res = JSON.parse(data)
// localStorage.setItem('userinfo', res.data.sessionToken)
// open('./user.html')
// }
// })
}
</script>
</body>
</html>
3.登录成功后跳转用户页,在请求头添加token请求用户页
请求用户接口需要添加请求头 Authorization: localStorage.getItem("userinfo")才可以获取用户数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户页</title>
</head>
<body>
<span id="user"></span>
<script src="./ajax.js"></script>
<script>
fetch("接口地址", {
method: "POST",
headers: { "Authorization": localStorage.getItem("userinfo") },
}).then(res => res.json())
.then(res => {
console.log(res.data.list);
})
// ajax({
// url: "接口地址", // 地址
// type: "POST", // 请求方式
// async: true, // 同步:false,异步:true
// headers: {
// Authorization: localStorage.getItem("userinfo")
// },
// success: function (data) { // 返回接受信息
// const res = JSON.parse(data)
// console.log(res.data.list);
// }
// })
</script>
</body>
</html>
因为懒所以都是通过id名.value获取元素,严谨一些还是通过document.getElementById('id名')获取元素