在React中,是否有一种方法可以将过滤器应用于通过提取获得的响应?
使用React 16.12.0。我们有许多类似于
const handleFormSubmit = (e) => {
e.preventDefault()
if (password != passConfirm) {
//handle password doesn't match password confirm on submit
setErrors({passConfirm: ["Must match password"]})
return
}
fetch(REACT_APP_PROXY + '/users/', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': `Token ${sessionStorage.getItem('token')}`},
body: JSON.stringify({first_name, last_name, username, password, email})
}).then((response) => {
if (response.ok) {
sessionStorage.setItem('token', response['Refresh-Token'])
setRedirect(true)
} else {
setErrors(response)
console.log(response)
}
})
“ .ok”响应的部分,
sessionStorage.setItem('token', response['Refresh-Token'])
我们将拥有许多此类端点,我们将需要提取此响应标头并将其放在本地存储中。是否有一种更优雅的方式将响应过滤器应用于某些端点以实现此行为而不是我们现在这样做的方式?
Using React 16.12.0. We have a number of fetch calls that resemble
const handleFormSubmit = (e) => {
e.preventDefault()
if (password != passConfirm) {
//handle password doesn't match password confirm on submit
setErrors({passConfirm: ["Must match password"]})
return
}
fetch(REACT_APP_PROXY + '/users/', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': `Token ${sessionStorage.getItem('token')}`},
body: JSON.stringify({first_name, last_name, username, password, email})
}).then((response) => {
if (response.ok) {
sessionStorage.setItem('token', response['Refresh-Token'])
setRedirect(true)
} else {
setErrors(response)
console.log(response)
}
})
Note the section where we have an ".ok" response
sessionStorage.setItem('token', response['Refresh-Token'])
We will have a number of these endpoints where we will want to extract this response header and place it in local storage. Is there a more elegant way of applying a response filter to certain endpoints to implement this behavior as opposed to the way we are doing it now?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为除了猴子修补本身以外,使用fetch没有可能的可能性:
但是,一定有人已经这样做了,所以我偶然发现了这个NPM库 fetth-Intercept 您可以使用类似的方法:
请注意以下内容:您需要需要
fetch--拦截
在使用Fetch
第一次之前。I don't think there is a possibility for this using fetch except monkey patching fetch itself:
But, there must be someone that already did this, so I stumbled upon this npm library fetch-intercept that you can use to do the similar:
Please be aware of the following: You need to require
fetch-intercept
before you usefetch
the first time.如果您愿意从
fetch
切换到axios
,则可以使用拦截器并在全球处理。参考: https://axios-http.com/docs/interpectors
If you are willing to switch from
fetch
toaxios
, you can use interceptors and handle it globally.Reference: https://axios-http.com/docs/interceptors
使用功能。
Use a function.