用fetch实现简易的Postman

80 阅读1分钟

fetch实现简易的Postman

fetch 是一个用于发起网络请求的内置函数。它返回一个 Promise,这个 Promise 解析(resolve)为 Response 对象,该对象表示来自服务器的响应。fetch 是基于 Promise 设计的,用于替代传统的 XMLHttpRequest,使得处理网络请求变得更加简洁和易于理解。

使用fetch发送请求:

            const url = document.getElementById('url').value;//获取url
            const method = document.getElementById('method').value;//请求的方式GET/POST
            const data = document.getElementById('data').value;//请求的参数

            let options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json' // 根据需要修改或添加其他头  
                }
            };

            if (method === 'POST') {
                options.body = JSON.stringify({ data: data }); // 假设我们发送JSON格式的数据  
            }

            fetch(url, options)
                .then(response => response.json()) // 假设服务器返回JSON  
                .then(data => {
                    document.getElementById('response').textContent = JSON.stringify(data, null, 2);
                })
                .catch(error => {
                    document.getElementById('response').textContent = 'Error: ' + error;
                });
        }

html:

        <label for="url">URL:</label>
        <input type="text" id="url" name="url" required><br><br>

        <label for="method">Method:</label>
        <select id="method" name="method">
            <option value="GET">GET</option>
            <option value="POST">POST</option>
        </select><br><br>

        <label for="data">Data (For POST):</label>
        <textarea id="data" name="data"></textarea><br><br>

        <button type="button" onclick="sendRequest()">Send Request</button>
    </form>