D:\code_gitee\html_crostest\htmo_crostest\index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
D:\code_gitee\html_crostest\htmo_crostest\src\main.ts
import { socket } from "./mysocketio";
import "./style.css";
import { axiosInstance } from "./myaxios";
document.querySelector<HTMLDivElement>("#app")!.innerHTML = `
<div>
<button id='send'>发送axios请求</button>
<button id='send-socket'>发送socket请求</button>
</div>
`;
document.getElementById("send")!.addEventListener("click", async () => {
const res = await axiosInstance.get("/");
const oRes = document.createElement("div");
oRes.innerHTML = res.data;
document.querySelector<HTMLDivElement>("#app")!.appendChild(oRes);
});
document.getElementById("send-socket")!.addEventListener("click", async () => {
socket.emit("join", "hello! ~~from clien");
const oRes = document.createElement("div");
oRes.innerHTML = "socket发送成功";
document.querySelector<HTMLDivElement>("#app")!.appendChild(oRes);
});
socket.on("join", (payload) => {
const oRes = document.createElement("div");
oRes.innerHTML = payload.data;
document.querySelector<HTMLDivElement>("#app")!.appendChild(oRes);
});
D:\code_gitee\html_crostest\htmo_crostest\src\myaxios.ts
import axios from "axios";
export const axiosInstance = axios.create({
baseURL: "http://127.0.0.1:9998",
timeout: 1000,
});
D:\code_gitee\html_crostest\htmo_crostest\src\mysocketio.ts
import { io } from "socket.io-client";
export const socket = io("http://localhost:9998/");
标签:axios,const,socket,cros,test,document,crostest,oRes
From: https://www.cnblogs.com/zhuoss/p/17054082.html