我可能忽略了明显的情况,但是有什么方法可以获得提取请求吗?(不是答复)。
正常的抓取看起来是这样的:
fetch(url, {
method: method,
headers: new Headers({
'Authorization': token,
'Content-Type': 'application/json'
}),
body: payload
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
我想要获得方法、头、正文和数据的能力,这些数据被传递来获取一个变量,这个变量可以传递给其他方法,比如日志。
发布于 2021-06-29 14:49:59
您无法从对象获得请求信息( fetch
的承诺已经实现),但是您可以自己构建一个对象,传递它,然后将它与fetch
一起使用。Request
构造函数接受与fetch
相同的参数,但它没有执行操作,而是返回它的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脚炮。fetch
不会拒绝它对HTTP错误的承诺,只会拒绝网络错误;您必须自己检查HTTP错误。在我的博客文章http://blog.niftysnippets.org/2018/06/common-fetch-errors.html中有更多。)
https://stackoverflow.com/questions/68180969
复制相似问题