Npm 请求
Npm 软件包, 请求 api 。 轻快而安全. 用本地打字码来写,不使用依赖性.
包装
- npm 运行构建
- 在工程根文件夹中复制文件"/build/package name-x.x.x.tgz".
- 在"package.json"文件中插入:"@cimo/package name":"文件:package name-x.x.x.tgz"
发布
- npm 运行构建
- npm 登录 -- auth- type=legacy
- npm 发布 -- auth- type=legacy -- 访问公众
安装
- Npm 软件包链接 - > https://www.npmjs.com/package/@cimo/request (中文(简体) )
重设
- 从根中删除此内容 :
- 数字
- 节点( 模块)
- 软件包锁.json
客户端
- 客户端.ts
...
import { Cr } from "@cimo/request/dist/src/Main";
...
const cr = new Cr("https://localhost");
cr.setRequestInterceptor((config) => {
//...
return {
...config,
headers: {
...config.headers,
"Accept-Language": "en,ja;q=0.9"
}
};
});
cr.setResponseInterceptor((response) => {
// ...
if (response.ok) {
// Success
} else {
// Fail
}
return response;
});
...
const data = {
token_api: "abc123",
name: "test",
};
cr.post("/test_post_json",
{
headers: {
"Content-Type": "application/json"
}
},
data
)
.then((data) => {
// Response
})
.catch((error: Error) => {
// Error
});
...
const formData = new FormData();
formData.append("token_api", "abc123");
formData.append("name", "test");
// In case of file upload, just delete the headers content-type parameter.
cr.post("/test_post_form-data",
{
headers: {
"Content-Type": "multipart/form-data"
}
},
formData
)
.then((data) => {
// Response
})
.catch((error: Error) => {
// Error
});
...
cr.get("/test_get", {})
.then((data) => {
// Response
})
.catch((error: Error) => {
if (error.cause === 401) {
// Unauthorized
}
});
// put, delete, patch
...
const data = {
name: "test",
};
cr.stream("/test_stream",
{
headers: {
"Content-Type": "application/json"
}
},
data
)
.then(async (reader) => {
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { value, done } = await reader.read();
...
buffer += decoder.decode(value, { stream: true });
const lineList = buffer.split(/\r?\n/);
buffer = lineList.pop() as string;
...
}
});
...