如何强制 JavaScript fetch api 在桌面模式下请求页面?

问题描述 投票:0回答:1

我使用 JavaScript fetch api 从 Reddit 的公共 json 端点下载 json 文件。 最近,Reddit 根据浏览器处于桌面模式还是移动模式,使其 json 端点做出不同的响应。如果浏览器处于移动模式,我的应用程序现在在大多数情况下都会从 Reddit 接收虚假数据,而在桌面模式下我的应用程序会收到正确的数据。

如何强制 fetch() 调用在桌面模式下发出请求?

javascript fetch-api reddit
1个回答
0
投票

您可以执行以下操作:

// Replace this value to your api address.
var Address = 'https://stackoverflow.com';
// Set the options for the `fetch` api.
var Options =
{
   headers:
   {
      // Replace this value to any desktop user agent.
      'User-Agent': 'Put any desktop agent here',
      
      // Or replace any other header that can make the
      // Reddit api return the contents for desktop.
   },
   mode: 'no-cors', // Change this according to your needs.
};

fetch(Address, Options).then
(
   Fetched => console.log('Retrieved content:', Fetched),
   Issue => console.log('Issue happened:', Issue?.message ?? Issue),
);

© www.soinside.com 2019 - 2024. All rights reserved.