
Product
Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.
@ymir-labs/http
Advanced tools
Axios 轻量级封装,提供易用的Ajax方法。
pnpm install @ymir-labs/http
import { http } from '@ymir-labs/http'
const userId = 'user-123'
const deptId = 'dept-1'
const user = await http.get('/user-info', { params: { userId, deptId } })
以上代码发送 /user-info?userId=user-123&deptId=dept-1
请求。user
是接口返回的JSON数据对象。例如返回以下JSON数据:
{
"userName": "张三",
"deptName": "A部门"
}
那么通过以下方式就可以获取数据:
console.log(`${user.userName}, ${user.deptName}`)
推荐指定响应数据类型,如下所示:
import { http } from '@ymir-labs/http'
/**
* 用户信息
*/
interface User {
/**
* 用户id
*/
userId: string
/**
* 用户名称
*/
userName: string
/**
* 部门id
*/
deptId: string
/**
* 部门名称
*/
deptName: string
}
const user = http.get<User>('/user-info', { params: { userId, deptId }})
import { http } from '@ymir-labs/http'
interface TodoItem {
id: string
title: string
status: 'todo' | 'done'
}
const todo = { title: '待办事项1', status: 'todo' }
const addedTodo = await http.post<TodoItem>('/todos', todo)
const updatingTodo = { ...addedTodo, status: 'done' }
const updatedTodo = await http.put<TodoItem>(`/todos/${updatingTodo.id}`, updatingTodo)
const todoId = 'todo-1'
const result = await http.delete(`/todos/${todoId}`)
目前有三种数据传递方式:
请求参数一般用于传递查询参数、过滤条件,也会在更新、删除请求中用于传递一些独立的参数。如:
http://url/todos?page=3&size=15
上面的 url 中,有两个请求参数,即page
和size
,分别是3
和15
.对应如下代码:
import http from '@ymir-libs/http'
const page = 3
const size = 15
const todos = await http.get('/todos', { params: { page, size }})
在 POST、PUT、DELETE 时传递请求参数时,要格外小心,应该以如下的方式传递请求参数:
import http from '@ymir-libs/http'
// 请求参数
const id = 'xxx'
const jsbm = '部门1,部门2'
// 需要提交的数据
const data = {}
const result = await http.post('/demo', data, {
params: { id, jsbm }
})
如果需要传递一组数据,则 http 会做以下序列化:
const ids = ['1', '2', '3']
await http.get('/demo', { params: { ids }})
发送的请求链接为:/demo?ids=1&ids=2&ids=3
。
路径参数一般用于在 url 路径部分添加资源 id,如下所示:
import http from '@ymir-libs/http'
const todoId = 'todo-1'
await http.put(`/todos/${todoId}`)
await http.delete(`/todos/${todoId}`)
我们在实际业务场景中,频繁使用一种请求体格式,即application/json
。
http
已经做了 json 的自动处理,只需要在post
、put
方法的第二个参数传递一个对象,http
就会自动将此 js 对象转换成 JSON 字符串传递给后端。
import http from '@ymir-libs/http'
const requestBody = { userName: 'jacking' }
const result = await http.post(url, requestBody)
谨记: 在做实际开发时,一定要仔细阅读相关 API 约束,确定需要传递参数的数据结构。
import http from '@ymir-libs/http'
const file = document.getElementById('file').files[0]
const result = await http.sendFile('/apis/files', file)
发送的是POST请求。
import http from '@ymir-libs/http'
const blob = new Blob(["Hello, World!"], { type: 'text/plain' })
const result = await http.sendFile('/apis/files', blob)
有一些file不是由表单产生的,而是由其他方式产生的。例如:
import http from '@ymir-libs/http'
const blob = new Blob(["Hello, World!"], { type: 'text/plain' })
const file = new File([blob], 'demo.txt', { type: 'text/plain' })
const result = await http.sendFile('/apis/files', file)
上传时添加额外数据:
import http from '@ymir-libs/http'
http.sendFile('/apis/files', file, {
// 上传时传递的额外数据
data: {
userId: '123',
userName: 'zhangsan',
},
})
import http from '@ymir-libs/http'
const onUploadProgress = (progressEvent: ProgressEvent) => {
console.log(
`上传进度:${((progressEvent.loaded / progressEvent.total) * 100) | 0}%`,
)
}
await sendFile(url, files, {
onUploadProgress,
})
响应码为2xx
的均认为是响应成功,其他的响应码均认为是错误,会抛出错误,如下所示:
import { isHttpError, errorMessage } from '@ymir-libs/http'
try {
const result = await http.post('/demo')
} catch (error) {
if (isHttpError(error)) {
console.log(`http错误,响应状态码:${error.statusCode},响应内容:${error.}`)
}
}
import http, { isHttpError } from '@ymir-libs/http'
const removeListener = http.onFailure(error => {
if (isHttpError(error) && error.response.status === 401) {
console.log('未登录,跳转到登录页')
}
throw error
})
// 取消错误监听
removeListener()
import { isHttpError, errorMessage } from '@ymir-libs/http'
try {
const result = await http.post('/demo')
} catch (error) {
console.log(errorMessage(error, '失败啦'))
}
import http from '@ymir-libs/http'
const removeListener = http.onResponse((response) => {
console.log(`接收到响应:${response.data}`)
return response
})
// 取消响应监听
removeListener()
FAQs
简易的Ajax库。
We found that @ymir-labs/http demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 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.
Product
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.
Research
Socket uncovers malicious Rust crates impersonating fast_log to steal Solana and Ethereum wallet keys from source code.
Research
A malicious package uses a QR code as steganography in an innovative technique.