Files
vue-ts-example/src/pages/Page/API.page.vue
严浩 cc0e5679a9 feat(xml): 增加 XML 解析和处理功能
- 添加了处理 XML 请求和响应的工具函数
- 实现了 GET 和 POST 请求的 XML 解析和返回
- 更新了 API 页面,增加了 XML POST 请求和解析的示例
- 优化了 XML 生成和转义逻辑,防止二次转义
2025-09-02 16:19:31 +08:00

165 lines
5.2 KiB
Vue
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.

<script setup lang="ts">
import axios from 'axios';
const baseURL = '/fake-api';
let fakeApiResult = $ref<null | Record<string, unknown>>(null);
onMounted(() => {
fetch(`${baseURL}/mock/get-user-info`)
.then((response) => response.json())
.then((json) => (fakeApiResult = json));
});
// 使用 axios 请求 XML并演示以文本获取后用 DOMParser 解析
// 选择此方式的原因:可控性更强,便于处理编码、容错与字段抽取策略
let xmlText = $ref<string | null>(null);
let xmlParsed = $ref<Record<string, string> | null>(null);
let xmlPostText = $ref<string | null>(null);
let xmlPostParsed = $ref<Record<string, string> | null>(null);
let xmlPostXmlText = $ref<string | null>(null);
let xmlPostXmlParsed = $ref<Record<string, string> | null>(null);
onMounted(async () => {
try {
const res = await axios.get<string>(`${baseURL}/xml/sample`, {
responseType: 'text',
headers: { Accept: 'application/xml' },
transformResponse: [(data: string) => data],
params: {
to: 'Alice',
from: 'Bob',
heading: 'Greeting',
body: 'Hello from API.page.vue',
id: '1001',
createdAt: new Date().toISOString(),
},
});
xmlText = res.data;
// 将 XML 字符串解析为 Document再选择性抽取业务所需字段
const doc = new DOMParser().parseFromString(res.data, 'application/xml');
const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
xmlParsed = {
to: pick('to'),
from: pick('from'),
heading: pick('heading'),
body: pick('body'),
id: pick('meta > id'),
createdAt: pick('meta > createdAt'),
};
// 备用方案:直接请求为 Document部分运行环境可能不支持
// const docRes = await axios.get<Document>(`${baseURL}/xml/sample`, { responseType: 'document' });
// console.log('Document:', docRes.data);
} catch (error) {
console.error('XML 请求失败: ', error);
}
});
// 演示 POST 提交 JSON由服务端返回 XML再解析
onMounted(async () => {
try {
const res = await axios.post<string>(
`${baseURL}/xml/submit`,
{
to: 'Tom',
from: 'Jerry',
heading: 'PostXML',
body: 'This is a POST body to XML service',
id: '9001',
createdAt: new Date().toISOString(),
},
{
headers: { 'Content-Type': 'application/json', Accept: 'application/xml' },
responseType: 'text',
transformResponse: [(data: string) => data],
},
);
xmlPostText = res.data;
const doc = new DOMParser().parseFromString(res.data, 'application/xml');
const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
xmlPostParsed = {
to: pick('to'),
from: pick('from'),
heading: pick('heading'),
body: pick('body'),
id: pick('meta > id'),
createdAt: pick('meta > createdAt'),
};
} catch (error) {
console.error('XML POST 请求失败: ', error);
}
});
// 演示 POST 以 XML 请求体提交,服务端解析 XML 并返回规范化的 XML
onMounted(async () => {
try {
const payload = `<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>XML-Client</to>
<from>Browser</from>
<heading>XMLSubmit</heading>
<body>Send by XML body</body>
<meta>
<id>777</id>
<createdAt>${new Date().toISOString()}</createdAt>
</meta>
</note>`;
const res = await axios.post<string>(`${baseURL}/xml/submit`, payload, {
headers: { 'Content-Type': 'application/xml', Accept: 'application/xml' },
responseType: 'text',
transformResponse: [(data: string) => data],
});
xmlPostXmlText = res.data;
const doc = new DOMParser().parseFromString(res.data, 'application/xml');
const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
xmlPostXmlParsed = {
to: pick('to'),
from: pick('from'),
heading: pick('heading'),
body: pick('body'),
id: pick('meta > id'),
createdAt: pick('meta > createdAt'),
};
} catch (error) {
console.error('XML POST(XML body) 请求失败: ', error);
}
});
/* fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((json) => console.log(json)); */
// let npmRegistryApiResult = $ref<Record<string, any> | null>(null);
// fetch('/npm-registry-api/@vue%2Fbabel-plugin-jsx')
// .then((response) => response.json())
// .then((json) => npmRegistryApiResult = json);
</script>
<template>
<pre>{{ JSON.stringify(fakeApiResult, null, 2) }}</pre>
<!-- <div>{{ npmRegistryApiResult?.['_id'] }}</div> -->
<h3>XML 字符串</h3>
<pre class="break-all whitespace-pre-wrap">{{ xmlText }}</pre>
<h3>解析后的结果</h3>
<pre>{{ xmlParsed }}</pre>
<h3>POST 返回的 XML 字符串</h3>
<pre class="break-all whitespace-pre-wrap">{{ xmlPostText }}</pre>
<h3>POST 解析后的结果</h3>
<pre>{{ xmlPostParsed }}</pre>
<h3>POST(XML body) 返回的 XML 字符串</h3>
<pre class="break-all whitespace-pre-wrap">{{ xmlPostXmlText }}</pre>
<h3>POST(XML body) 解析后的结果</h3>
<pre>{{ xmlPostXmlParsed }}</pre>
</template>
<style scoped></style>