Files
nxxmdata/test-frontend-logout.js

118 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 测试前端退出登录功能
const axios = require('axios');
// 登录信息
const credentials = {
username: 'admin',
password: '123456',
remember: false
};
// 后端API地址
const API_BASE_URL = 'http://localhost:5352/api';
// 模拟前端登录
async function login() {
try {
console.log('模拟前端登录...');
const response = await axios.post(`${API_BASE_URL}/auth/login`, credentials);
if (response.data && response.data.code === 200) {
const token = response.data.data.token;
console.log('登录成功获取到token:', token);
return token;
} else {
console.error('登录失败:', response.data?.message || '未知错误');
return null;
}
} catch (error) {
console.error('登录请求失败:', error.message);
return null;
}
}
// 模拟前端调用退出登录接口
async function logout(token) {
try {
console.log('模拟前端调用退出登录接口...');
const response = await axios.post(`${API_BASE_URL}/auth/logout`, {}, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.data && response.data.code === 200) {
console.log('退出登录成功:', response.data.message);
return true;
} else {
console.error('退出登录失败:', response.data?.message || '未知错误');
return false;
}
} catch (error) {
console.error('退出登录请求失败:', error.message);
return false;
}
}
// 验证token是否失效
async function verifyToken(token) {
try {
console.log('验证退出登录后token是否失效...');
const response = await axios.get(`${API_BASE_URL}/auth/userinfo`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.data && response.data.code === 200) {
console.error('警告退出登录后token仍然有效可以获取用户信息');
return false;
} else {
console.log('验证成功退出登录后token已失效');
return true;
}
} catch (error) {
if (error.response && error.response.status === 401) {
console.log('验证成功退出登录后token已失效返回401错误');
return true;
} else {
console.error('验证token失败:', error.message);
return false;
}
}
}
// 主测试函数
async function runTest() {
try {
// 1. 登录获取token
const token = await login();
if (!token) {
console.log('测试失败无法获取登录token');
return;
}
// 2. 调用退出登录接口
const logoutSuccess = await logout(token);
if (!logoutSuccess) {
console.log('测试失败:退出登录接口调用失败');
return;
}
// 3. 验证token是否失效
const tokenInvalid = await verifyToken(token);
if (tokenInvalid) {
console.log('\n测试成功前端退出登录功能正常工作');
console.log('1. 登录成功获取到token');
console.log('2. 退出登录接口调用成功');
console.log('3. 退出登录后token已失效');
} else {
console.log('\n测试失败前端退出登录功能存在问题');
}
} catch (error) {
console.error('测试过程中发生错误:', error);
}
}
// 运行测试
runTest();