# node-phax **Repository Path**: towardly/node-phax ## Basic Information - **Project Name**: node-phax - **Description**: nodejs 上实现 fetch API ,同时做了简单的封装,高效、简单、易用 - **Primary Language**: NodeJS - **License**: MulanPSL-1.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-08-14 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # node-phax ### 介绍 nodejs 上实现 fetch API ,同时做了简单的封装,高效、简单、易用。 ### 描述 基于浏览器端 [phax](https://github.com/DvShu/phax "phax") 实现了 `NodeJs` 端的 `HTTP` 请求。同时也实现了 `Nodejs` 端的 `fetch` 实现。 ### 安装 ``` npm install node-phax yarn add node-phax ``` ### 使用 ``` const phax = require('node-phax'); phax(url, options).then(data => {}).catch(err => {}); ``` 如果返回的状态标识 *ok* 为 *true*(status >= 200 & status < 300) 则会返回调用 *res.json()*、*res.text()* 之后的结果 ### 接口参数说明 1. `phax(url[, accept])`: - *url*:_String_ **必填** 请求地址 - *accept*:_String_ **选填** 接收的返回数据的格式,会把返回的数据解析为对应的格式,对应着 [Response](https://developer.mozilla.org/zh-CN/docs/Web/API/Response)的返回函数(`Body.text()` --> *text*……) ,例如:json、text;如果不填会根据返回的数据的头部( `Headers` )中的 `Content-Type` 字段来确认,如果 `Content-Type` 的值为 `application/json` 则调用 `res.json()` 返回 *json* 格式的数据 2. `phax(url, options)` 3. `phax(options)`: + *options*:_Object_ 请求配置,在基于 *fetch* 的配置的基础上额外支持3个配置 1. json: *Object|String* 当需要上传 *json* 格式的参数时传递,会自动将请求的 `Content-Type` 填写为 `application/json;charset=UTF-8` 2. accept 3. url: 如果在调用函数的时候已经传递了 *url* 参数,则按传递的为准 ### 使用fetch ```Javascript const fetch = require('node-phax/lib/fetch'); function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new Error(response.statusText) error.response = response throw error } } function parseJSON(response) { return response.json() } fetch('/users') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('request succeeded with JSON response', data) }) .catch(function(error) { console.log('request failed', error) }) ``` 支持的配置: ``` { method, body, headers, auth, agent, createConnection, timeout } ``` 其中 *method*、*body*、*headers* 是 [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Request)所支持的参数。*auth*、*agent*、*createConnection*、*timeout* 是 [nodejs http](https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_http_request_options_callback)所支持的参数 #### 与浏览fetch的区别 1. 浏览器端 fetch get 请求传参数会报错;而这个库,会识别 _body_ 参数,如果 _body_ 参数是 _String_ 类型的则会将参数拼接到 _url_ 后面,否则会将参数通过 [querystring.stringify()](https://nodejs.org/dist/latest-v10.x/docs/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) 序列化后拼接到 url 后面 ### 参考工程 1. [node-fetch](https://github.com/bitinn/node-fetch "node-fetch") 2. [github_fetch](https://github.com/github/fetch "fetch")