获取获取请求

Get Fetch Request

我可能忽略了显而易见的东西,但有没有办法获取获取请求? (不是回应)。

正常的抓取看起来像这样:

fetch(url, {
                method: method,
                headers: new Headers({
                    'Authorization': token,
                    'Content-Type': 'application/json'
                }),
                body: payload
            })
            .then((response) => response.json())
            .then((responseData) => {
                
                console.log(responseData);
            })

我想要获取方法的能力,headers,body,并且是传递给 fetch 的变量中的数据,该变量可以传递给其他方法,例如日志。

你不能自己从Response object (the thing the promise from fetch is fulfilled with), but you can build a Request object获取请求信息,传递它,然后将其与fetch一起使用。 Request 构造函数接受与 fetch 相同的参数,但它不是执行操作,而是 returns 它的 Request 对象。

例如,您的代码是这样完成的:

// Building the request, which you can then pass around
const request = new Request(url, {
    method: method,
    headers: new Headers({
        "Authorization": token,
        "Content-Type": "application/json"
    }),
    body: payload
});

// Using it
fetch(request)
.then((response) => {
    if (!response.ok) { // Don't forget this part!
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
})
.then((responseData) => {
    console.log(responseData);
});

(旁白:注意上面第一个履行处理程序的轻微添加,以处理 fetch API footgun。fetch 不会拒绝它的承诺关于 HTTP 错误,只有网络错误;您必须自己检查 HTTP 错误。更多内容在我的博客中 post here。)