某些请求标题

发布于 2025-01-27 14:44:57 字数 828 浏览 4 评论 0原文

我正在从事一些项目,遇到了一个问题。 主要问题是:

当我通过在浏览器处键入API端点时,它会加载返回的HTML页面。 但是,如果我使用onclick侦听器中的fetch api击中相同的终点,则不会加载页面。我相信HTML页面是作为响应的一部分到达的。

我调查了问题,以查看导致它的原因。我意识到,当浏览器提出请求与提取API提出请求时,请求标头略有不同。

主要区别是: 浏览器版本:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1

Fetch API版本:

Accept: */*
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

我尝试修改这些特定的标头以匹配获取请求中的浏览器版本,但是,无论我尝试了多少,它们都没有更改。

我现在知道该怎么做才能获得所需的功能。我可以使用Windows。Location并进行浏览器重新加载,也可以在Express JS服务器中使用重定向功能。

我要问的是: 这些标头是什么使我的HTML页面使用Fetch API从按钮发送请求时不加载? 这些标题在做什么? 如果是这样,它们是否不可修改?

I am working on some projects and I came across a problem.
The main problem is this:

When I go to an API end-point by typing the at the browser, it loads the html page returned.
However, if I hit the same end-point using the Fetch API in an onclick listener, it does not load the page. I am sure the html page arrives as a part of the response tho.

I investigated the problem to see what is causing it. I realized that the request headers differ slightly when the browser is making the request vs fetch api making the request.

The main difference is this:
Browser version:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1

Fetch API version:

Accept: */*
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

I tried modifying these specific headers to match the browser version in the fetch request however, no matter how much I tried, they did not change.

I now know what to do to get the desired functionality. I can either use windows.location and make browser reload or I can use redirect function in my express js server.

What I am asking is this:
Are those headers what making my html page not load when the request is sent from a button using Fetch API?
What are those headers doing?
Are they not modifiable if so, why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文