我正在开发一个依赖于客户端的 Accept
header 的 Web 应用程序。在协商内容类型时,我的服务器更喜欢 text/plain
而不是 text/html
。
我想在 HTML 页面中添加一个下载按钮,该按钮会重定向到当前正在查看的页面。这次请求一个 text/plain
变体;服务器将设置 Content-Disposition
header ,启动下载。
问题是,例如Firefox 完全忽略了链接上的 type
属性,而本应做到这一点。 示例:
<a href=/ type=text/plain>Download</a>
GET /
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
GET /
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
最后一个请求来自点击下载链接,并且那里没有 text/plain
。
我已经成功地使用 JavaScript 创建了一个解决方法,但它充其量也很丑陋:
<a id=download download href=#>Download</a>
<script>
document.getElementById("download").onclick =
async () => {
// send the request manually instead of redirecting directly
const res = await fetch(window.location, { headers: { "Accept": "text/plain" } });
const text = await res.text();
// redirect to the file in memory
const file = new File([text], "hello.txt", { type: "application/octet-stream" });
window.location.assign(window.URL.createObjectURL(file));
};
</script>
这不可能是最终的解决方案,必须有更好的方法!
最佳答案
您误解了 type
属性的用途。
The rel, rev, hreflang, and type attributes may be used to indicate to the user the likely nature of the target resource before the user follows the link.
它告诉浏览器期望纯文本,而不是在Accept
header 中使用它。
HTML 没有提供控制 Accept
header 的机制。解决此问题的传统方法是使用不同的 URL。
例如:
http://example.com/example.html
HTMLhttp://example.com/example.txt
纯文本http://example.com/example
用于内容协商数据
Apache HTTP 有 MultiViews directive用于处理此问题。
关于javascript - 如何在没有默认 Accept header 的情况下重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226599/