Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
@ourea/fetch
Advanced tools
$ npm install @ourea/fetch --save
import Http, { HttpError } from '@ourea/fetch'
const http = Http(opt)
const options = {
config?: {
baseUrl: String, // 请求的前置 url,仅对相对路径做拼接
timeout: Number, // 超时时间 单位 ms
credentials: String, // fetch 的验证规则配置
headers: Object<key|value>, // 请求头配置
},
before?: (Function | Promise)[], // 前置钩子
after?: (Function | Promise)[], // 后置后盖
error?: Function | Promise, // 全局请求错误的错误钩子
wrapperFunc?: Function, // 对于特殊请求的包裹函数 不推荐使用
allow?: String[] // 允许使用的方法
}
配置 | 说明 | 默认值 | 其它 |
---|---|---|---|
allow | client 允许的请求类型 | ['get', 'post', 'put', 'delete', 'upload', 'download'] | 可选 |
before | 前置钩子(钩子数组) | [] | 可选 |
after | 后置钩子(钩子数组) | [] | 可选 |
config | fetch配置项 | 参考fetch api 文档 | |
error | 全局错误处理函数 | null | 可选 |
// 使用场景
import Http, { HttpError } from '@ourea/fetch'
// error hook 的返回值 将作为最终的错误体抛出到具体的业务端,在此处可以对error 进行具体的业务性质错误封装
http.setErrorHook(async (httpError, fetchUrl) => {
if (httpError.code === HttpError.ERROR_CODE.HTTP_STATUS_ERROR) {
const { msg, error, error_description } = await httpError.response.json()
return new HttpError({
message: msg | error_description | error,
code: httpError.httpStatus,
httpStatus: httpError.httpStatus,
})
}
console.log('[HTTP ERROR]', fetchUrl, httpError)
})
{ url, opt }
,返回值也必须为{ url, opt }
或者无返回throw new Error('find error in before hook .')
示例
http.injectBefore(({ url, opt }) => {
const { headers, params } = opt
const token = 'XXXXXXXX'
const auth = 'xxxxxxxx'
headers['Authorization'] = `Basic ${auth}`
headers['Token'] = `${token}`
return { url, opt: { ...opt, headers }}
})
200
的情况下才会执行,非200
的请求则直接跳转到errorHook
response
,若钩子函数返回的是HttpError
的实例的话,当前请求的promise会被reject,
这次请求的失败信息将也会触发onError事件HttpError
则后续的钩子则不会执行 http.injectAfter(rsp => {
try {
const { success, code, message, msg } = rsp
if (!success || code === 40101) {
if (code === 40101) { // 根据项目判断状态码
return new HttpError({
code,
httpStatus: HttpError.ERROR_CODE.TOKEN_EXPIRE, // 登录超时
message: message || msg || HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.TOKEN_EXPIRE],
})
} else if (code !== 0) {
return new HttpError({
code,
httpStatus: CUSTOM_HTTP_ERROR_STATUS, // 服务器返回的错误
message: message || msg || '后台返回未知错误',
})
}
}
} catch (error) {
return new HttpError({
code: CUSTOM_HTTP_ERROR_STATUS,
httpStatus: HttpError.RESPONSE_PARSING_FAILED, // 解析数据错误
message: HttpError.HTTP_ERROR_MAP[HttpError.ERROR_CODE.RESPONSE_PARSING_FAILED],
})
}
})
http.injectAfter(function(rsp){
// do some response check
return new vFetch.HttpError({
code: '001',
message: 'error test',
httpStatus: null,
})
})
HttpError
实例的构造函数为 http.HttpError
...
throw new http.HttpError({
code: "TOKEN_EXPIRE"
httpStatus: 401
message: "用户认证失败"
})
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../dist/vFetch.js"></script>
</head>
<body>
<script>
console.log(window, VFetch.HttpError, VFetch.HTTP_ERROR_MAP, VFetch.httpConfig)
const http = VFetch(VFetch.httpConfig)
http.injectAfter(function(rst){
console.log('injectAfter', rst)
return new vFetch.HttpError({
code: '001',
message: 'error test',
httpStatus: null,
})
})
http.injectAfter(function(){
console.log(222);
})
http.setErrorHook(async function(e){
console.log(e, 'error');
const timeoutPromise = new Promise(resolve => setTimeout(() => {
resolve('async hook')
}, 1000))
const data = await timeoutPromise
console.log(data)
})
http.get('t.json', {a:2, c:3}, { baseUrl, headers, timeout, ... })
.then(rst => {
//console.log(rst, 'success');
}).catch(e => {
//console.log(e, 'error');
})
</script>
</body>
</html>
FAQs
easy to use fetch lib
The npm package @ourea/fetch receives a total of 3 weekly downloads. As such, @ourea/fetch popularity was classified as not popular.
We found that @ourea/fetch demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.