欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > fetch请求代码

fetch请求代码

2025/4/29 15:44:11 来源:https://blog.csdn.net/weixin_62268437/article/details/144805966  浏览:    关键词:fetch请求代码

 用于方便与后端做简单的接口测试(参数编码与不编码)

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Fetch Request</title>
</head><body><button id="fetchButton">Fetch Data</button><div id="responseContainer"></div><script>// 定义 URL 和参数const baseUrl = 'http://10.30.20.146:20510/api/v1/text/page';const params = {// textName: '!@中国# $%^&/*\=()_+??><[]{}',textName: "!@中国人$%^_+??><`~!@#$%^&*()_-+=|\}{;:'/?.>,</*-+.[",array: [1, 2, 3],page: 1,pageSize: 20,domainType: 1,decode: 1};// 获取按钮元素const fetchButton = document.getElementById('fetchButton');fetchButton.addEventListener('click', () => {performRequest(baseUrl, params, false);});async function performRequest(url, params, encodeParams = true) {// 构建完整的 URLconst urlWithParams = buildUrlWithParams(url, params, encodeParams);console.log('===[[urlWithParams]]', urlWithParams);// 请求选项const options = {method: 'GET',headers: {'Accept': '*/*','Accept-Encoding': 'gzip, deflate, br','Connection': 'keep-alive','User-Agent': 'PostmanRuntime-ApipostRuntime/1.1.0','_appId': '1','_tenantId': '1','_userId': '3026601398293760000'}};try {const response = await fetch(urlWithParams, options);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();console.log('Response data:', data);displayResponse(data);} catch (error) {console.error('Fetch error:', error);}}function buildUrlWithParams(url, params, encodeParams) {const urlObj = new URL(url);for (const [key, value] of Object.entries(params)) {if (encodeParams) {urlObj.searchParams.append(key, encodeURIComponent(value));} else {urlObj.searchParams.append(key, value);}}return urlObj.toString();}function displayResponse(data) {const responseContainer = document.getElementById('responseContainer');responseContainer.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;}</script>
</body></html>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词