const http = require('http');
|
|
// 模拟小程序的GraphQL请求
|
function testGraphQLRequest(token) {
|
const mutation = `
|
mutation SaveUserInfo($input: SaveUserInfoInput!) {
|
saveUserInfo(input: $input) {
|
id
|
name
|
phone
|
gender
|
birthday
|
}
|
}
|
`;
|
|
const variables = {
|
input: {
|
name: "测试用户",
|
phone: "13981970816",
|
gender: "MALE",
|
birthday: "2025-10-07"
|
}
|
};
|
|
const postData = JSON.stringify({
|
query: mutation,
|
variables: variables
|
});
|
|
const options = {
|
hostname: 'localhost',
|
port: 8080,
|
path: '/api/graphql',
|
method: 'POST',
|
headers: {
|
'Content-Type': 'application/json',
|
'Content-Length': Buffer.byteLength(postData)
|
}
|
};
|
|
// 如果有token,添加Authorization头
|
if (token) {
|
options.headers['Authorization'] = `Bearer ${token}`;
|
console.log('发送请求,携带token:', token.substring(0, 20) + '...');
|
} else {
|
console.log('发送请求,不携带token');
|
}
|
|
const req = http.request(options, (res) => {
|
console.log('响应状态码:', res.statusCode);
|
console.log('响应头:', res.headers);
|
|
let data = '';
|
res.on('data', (chunk) => {
|
data += chunk;
|
});
|
|
res.on('end', () => {
|
console.log('响应内容:', data);
|
try {
|
const response = JSON.parse(data);
|
if (response.errors) {
|
console.log('GraphQL错误:', response.errors);
|
} else {
|
console.log('请求成功:', response.data);
|
}
|
} catch (e) {
|
console.log('解析响应失败:', e.message);
|
}
|
});
|
});
|
|
req.on('error', (e) => {
|
console.error('请求错误:', e.message);
|
});
|
|
req.write(postData);
|
req.end();
|
}
|
|
// 测试不同情况
|
console.log('=== 测试1: 不携带token ===');
|
testGraphQLRequest(null);
|
|
setTimeout(() => {
|
console.log('\n=== 测试2: 携带无效token ===');
|
testGraphQLRequest('invalid.token.here');
|
}, 2000);
|
|
setTimeout(() => {
|
console.log('\n=== 测试3: 携带格式正确但可能过期的token ===');
|
// 这里需要一个真实的token,可以从小程序中获取
|
const testToken = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiItMSIsInVzZXJJZCI6LTEsImlhdCI6MTcyODMwMjk5MCwiZXhwIjoxNzI4Mzg5MzkwfQ.test';
|
testGraphQLRequest(testToken);
|
}, 4000);
|