Files
huishou/test-api.mjs
T
2026-07-27 13:37:48 +08:00

120 lines
2.9 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.
import http from 'http';
// 测试后端订单查询接口
const testOrders = (collector) => {
return new Promise((resolve) => {
const options = {
hostname: 'hs.yifenbao.cn',
port: 4001,
path: `/api/orders${collector ? '?collector=' + encodeURIComponent(collector) : ''}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(data);
console.log(`测试查询(collector=${collector || '空'}:`);
console.log(`返回订单数: ${result.data?.length || 0}`);
if (result.data && result.data.length > 0) {
console.log(`第一个订单的collector: ${result.data[0].collector || '空'}`);
}
resolve(result);
} catch (e) {
console.log('解析失败:', data);
resolve(null);
}
});
});
req.on('error', (e) => {
console.error('请求失败:', e.message);
resolve(null);
});
req.end();
});
};
// 测试创建订单接口
const testCreateOrder = () => {
return new Promise((resolve) => {
const data = JSON.stringify({
items: [{
category: '001',
name: '纸类(书本)',
weight: 5,
unit: 'kg',
price: 1.2,
amount: 6
}],
totalWeight: 5,
totalPrice: 6,
city: '天津市',
district: '高新区',
community: '测试社区',
user: '测试用户',
collector: '宁赜'
});
const options = {
hostname: 'hs.yifenbao.cn',
port: 4001,
path: '/api/orders',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
};
const req = http.request(options, (res) => {
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
try {
const result = JSON.parse(responseData);
console.log('创建订单结果:', result);
resolve(result);
} catch (e) {
console.log('解析失败:', responseData);
resolve(null);
}
});
});
req.on('error', (e) => {
console.error('请求失败:', e.message);
resolve(null);
});
req.write(data);
req.end();
});
};
// 执行测试
(async () => {
console.log('=== 测试后端API ===\n');
console.log('1. 测试查询所有订单:');
await testOrders();
console.log('\n2. 测试查询宁赜的订单:');
await testOrders('宁赜');
console.log('\n3. 测试创建订单:');
await testCreateOrder();
console.log('\n4. 再次查询宁赜的订单:');
await testOrders('宁赜');
})();