10/13
JSONP Demo
原理及代码
使用 script 标签绕过浏览器 CORS 的限制。
前端定义回调函数,并通过query将回调函数名传给后端。
function showData({ date, msg }) {
const newData = document.createElement("div");
const title = document.createElement("h3"),
content = document.createElement("div");
title.append(`Date: ${date}`);
content.append(`Msg: ${msg}`);
newData.append(title, content);
document.querySelector("#container")?.append(newData);
}
function begin() {
const script = document.createElement("script");
script.src = "http://localhost:3000/jsonp?callback=showData";
document.body.append(script);
}
后端生成对应的JS代码 - 以数据为参数调用该回调函数。将处理后的js代码返回,浏览器接收后执行。
function generateJS(callbackName) {
const date = new Date().toISOString().split("T")[0];
const msg = "jsonp demo";
const js = `
${callbackName}({ date: "${date}", msg: "${msg}" });
`;
return js;
}
app.get(
"/jsonp",
(req, res) => {
const data = generateJS(req.query.callback);
res.setHeader("Content-Type", "text/javascript");
res.send(data);
},
);
encodeURI 与 encodeURIComponent的区别
encodeURI: 转义所有URL中不允许出现的字符;
encodeURIComponent: 除了encodeURI会转义的所有字符以外,额外转义#, $, &, +, ,, /, :, ;, =, ? 和 @。
示例:
const url = "http://localhost:5000/pathname?键名1=值1&键名2=值2";
// http://localhost:5000/pathname?%E9%94%AE%E5%90%8D1=%E5%80%BC1&%E9%94%AE%E5%90%8D2=%E5%80%BC2
encodeURI(url);
// http%3A%2F%2Flocalhost%3A5000%2Fpathname%3F%E9%94%AE%E5%90%8D1%3D%E5%80%BC1%26%E9%94%AE%E5%90%8D2%3D%E5%80%BC2
encodeURIComponent(url);
encodeURIComponent 主要用于保证 query 语义的正确性。例如:
const key = "a=key&b",
value = "value";
// ?a=key&b=value
`?${encodeURI(key)}=${encodeURI(value)}`;
// ?a%3Dkey%26b=value
`?${encodeURIComponent(key)}=${encodeURIComponent(value)}`;