在浏览器中通过 javascript 使用 Rest-API
我正在用 go 编写一个提供 Rest-API 的服务器应用程序。如果服务器得到一个没有 JSON-content-type 标头的 GET,它会提供一个空的 html 页面,其 head 中有一个 javascript 模块。此 JavaScript 代码使用 fetch 来使用 Rest-API,然后根据从服务器获取的内容填充 document.body。内容中的每个“链接”都会触发对 API 的进一步调用以及对内容的相应更新。
到目前为止,一切都很好。但我提出了两个令人恼火的观察结果。
(显然)浏览器的“后退”和“前进”按钮保持不活动状态。这似乎合乎逻辑,因为没有加载与内容更改相关的 URL。
如果我从其他页面进入 Rest-UI 并点击浏览器的后退按钮,我会按预期返回其他页面,但如果我现在点击浏览器的前进按钮,我会看到来自初始获取的 JSON 响应而不是我的 Rest-UI 内容。重新加载我的页面使一切恢复正常,但我无法向任何用户提供这种行为:)
是否有常见的方法来处理这种行为?例如,完全删除浏览器控件,使用 js 回调“手动”提供浏览器历史记录、缓存指令……(我对 js 缺乏经验)
I'm writing a sever application in go providing a Rest-API. If the server gets a GET without JSON-content-type header it serves an empty html-page having a javascript module in its head. This javascript code uses fetch to consume the Rest-API and populates then according the document.body with content fetched from the server. Each "link" in the content triggers further calls to the API and corresponding updates to the content.
So far so good. But I made two irritating observations.
(obviously) the "back" and "forward" buttons of the browser stay inactive. Which seems logical since there are no loaded URLs associated with the content changes.
If I come to my Rest-UI from an other page and hit the browser's back-button I get as expected the other page back but if I hit now the browser's forward-button I see the JSON-response from my initial fetch instead of my Rest-UI content. Reloading my page makes it all good again but I can't offer that behavior to any user :)
Are there common approaches to deal with this behavior? E.g. removing the browser controls completely, feeding the browser-history "by hand" with js-callbacks, caching directives, ... (I'm inexperienced with js)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题的根源是我在服务器端重载了 GET 请求的响应:如果 GET 请求接受 JSON,则服务器返回 JSON,否则它返回一个带有 javascript 的 html 页面,该 javascript 消耗 JSON。 IE。 JSON 的 javascript 获取是给定 URL 的最后一个 GET 响应,并因此进入与该 URL 关联的浏览器缓存中。对我来说有效的解决这个问题的方法是发送一个带有 JSON 响应的标头,关闭缓存并用“Vary”标头向浏览器发出信号,表明该响应取决于“Accept”标头。另一种解决方案可能是为 Rest 请求添加不同的端点到服务器。
The root of the problem is that I overloaded the response of a GET request on the server-side: if the GET-request accepts JSON the server returns JSON otherwise it returns a html-page with the javascript which consumes the JSON. I. e. the javascript fetch for the JSON is the last GET-response for a given URL and goes as such into the browser's cache associated with that URL. A solution to that problem which works for me is to send a header with the JSON response turning of caching and signalling the browser with the "Vary"-header that the response depends on the "Accept"-header. An other solution might be to add distinct endpoints to the server for the Rest-requests.