function render(){
const domain = new URLSearchParams(location.search).get("domain") || "fe.iodv.cn";
const [api, setApi] = useState(`https://${domain}/api/cookie`);
const [httpMethod, setHttpMethod] = useState("GET");
const [httpResult, setHttpResult] = useState("");
const [sendCookies, setSendCookies] = useState("");
const [cookieInfo, setCookieInfo] = useState({
name: "hello",
value: "world",
Domain: domain,
HttpOnly: false,
"Max-Age": 1200,
Path: "/",
SameSite: "Lax",
Secure: false
});
useEffect(() => {
console.log("cookieInfo: ", JSON.stringify(cookieInfo));
const cookies = Object.keys(cookieInfo)
.map(key => ({
key: key,
value: cookieInfo[key]
}))
.reduce((p, n) => {
if(!n.value){
return p;
}
if(httpMethod === "GET"){
p += `${n.key}=${encodeURIComponent(n.value)}&`;
} else {
p[n.key] = n.value;
}
return p;
}, httpMethod === "GET" ? "" : {});
setSendCookies(typeof cookies === "string" ? cookies : JSON.stringify(cookies));
}, [cookieInfo]);
const list = Object.keys(cookieInfo)
.map(key => ({
key: key,
value: cookieInfo[key],
}))
.map(kv => ({
...kv,
render: () => {
const t = typeof kv.value;
if(t === "boolean") {
return <input type="checkbox"
checked={kv.value}
onChange={e => setCookieInfo({ ...cookieInfo, [kv.key]: e.target.checked })} />
}
return <input type={t === "number" ? "number" : "text"}
value={kv.value}
onChange={e => setCookieInfo({ ...cookieInfo, [kv.key]: e.target.value })} />
}
}));
const send = async () => {
if(httpMethod !== "GET" && httpMethod !== "POST") {
setHttpResult(`请求方法必须是 GET 或者 POST (区分大小写).`);
return;
}
const origin = "origin=" + encodeURIComponent(location.origin);
const query = httpMethod === "GET"
? sendCookies + "&" + origin
: origin;
const response = await fetch([api, query].join("?"), {
method: httpMethod,
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: httpMethod === "POST" ? sendCookies : undefined
});
const json = await response.json();
setHttpResult(JSON.stringify(json, null, " "));
};
return (<div>
<h3>Cookie信息: </h3>
{ list.map(item => (<div key={item.key}>
<label>{item.key}: { item.render() } </label>
</div>)) }
<hr />
<h3>请求信息</h3>
<div> <label>接口地址: <input type="text" value={api} onChange={e => setApi(e.target.value)} /> </label> </div>
<div> <label>请求方法: <input type="text" value={httpMethod} onChange={e => setHttpMethod(e.target.value)} /> </label> </div>
<div>
<div>待传递Cookie值:</div>
<div>{sendCookies}</div>
</div>
<div> <button onClick={send}>发起请求</button> </div>
<hr />
<div> 返回结果: <br /> <pre>{httpResult}</pre> </div>
</div>);
}