2022-08-18 12:45:28 +03:00
|
|
|
# purescript-fetch
|
2022-08-18 23:08:19 +03:00
|
|
|
|
|
|
|
High-level library for the [WHATWG Fetch Living Standard](https://fetch.spec.whatwg.org/).
|
|
|
|
|
2022-08-19 20:34:05 +03:00
|
|
|
`purescript-fetch` works on browser and Node.js.
|
|
|
|
Running on Node.js requires version `>17.5`, see [# Usage](#usage).
|
2022-08-19 18:42:11 +03:00
|
|
|
|
|
|
|
## Installation
|
2022-08-18 23:08:19 +03:00
|
|
|
|
|
|
|
```bash
|
|
|
|
spago install fetch
|
|
|
|
```
|
2022-08-19 18:42:11 +03:00
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
**Note:**
|
|
|
|
Node.js `<17.5` is not supported.
|
|
|
|
Node.js `>=17.5` and `<18.0` requires the `--experimental-fetch` node options:
|
|
|
|
```bash
|
|
|
|
NODE_OPTIONS=--experimental-fetch spago run
|
|
|
|
```
|
2022-09-08 04:10:55 +03:00
|
|
|
Node.js `>=18.0` you don't need to set the `--experimental-fetch` node option.
|
2022-08-19 18:42:11 +03:00
|
|
|
|
|
|
|
Perform a simple `GET` request:
|
|
|
|
```purescript
|
|
|
|
fetch "https://httpbin.org/get" {} >>= _.text
|
|
|
|
```
|
|
|
|
|
|
|
|
Perform a `POST` request:
|
|
|
|
```purescript
|
|
|
|
do
|
|
|
|
{ status, text } <- fetch "https://httpbin.org/post"
|
|
|
|
{ method: POST
|
|
|
|
, body: """{"hello":"world"}"""
|
|
|
|
, headers: { "Content-Type": "application/json" }
|
|
|
|
}
|
|
|
|
responseText <- text
|
|
|
|
```
|
|
|
|
|
|
|
|
### Json parsing
|
|
|
|
|
|
|
|
`fetch` works well with `yoga-json` and `argonaut`, use our little helper libraries.
|
|
|
|
|
2022-08-26 16:10:09 +03:00
|
|
|
|
2022-08-19 18:42:11 +03:00
|
|
|
### yoga-json
|
2022-08-20 22:13:57 +03:00
|
|
|
|
|
|
|
```bash
|
|
|
|
spago install fetch-yoga-json
|
|
|
|
```
|
2022-08-19 18:42:11 +03:00
|
|
|
|
|
|
|
```purescript
|
2022-08-20 22:13:57 +03:00
|
|
|
type HttpBinResponse = { json :: { hello :: String } }
|
|
|
|
|
|
|
|
main :: Effect Unit
|
|
|
|
main = launchAff_ do
|
|
|
|
{ json } <- fetch "https://httpbin.org/post"
|
|
|
|
{ method: POST
|
2022-08-23 20:50:02 +03:00
|
|
|
, body: writeJSON { hello: "world" }
|
2022-08-20 22:13:57 +03:00
|
|
|
, headers: { "Content-Type": "application/json" }
|
|
|
|
}
|
|
|
|
{ json: { hello: world } } :: HttpBinResponse <- fromJSON json
|
|
|
|
log world
|
2022-08-19 18:42:11 +03:00
|
|
|
```
|
2022-08-19 20:35:13 +03:00
|
|
|
|
|
|
|
### argonaut
|
|
|
|
|
2022-08-20 22:13:57 +03:00
|
|
|
```bash
|
|
|
|
spago install fetch-argonaut
|
|
|
|
```
|
|
|
|
|
|
|
|
```purescript
|
|
|
|
type HttpBinResponse = { json :: { hello :: String } }
|
|
|
|
|
|
|
|
do
|
|
|
|
{ json } <- fetch "https://httpbin.org/post"
|
|
|
|
{ method: POST
|
2022-08-23 20:50:02 +03:00
|
|
|
, body: toJsonString { hello: "world" }
|
2022-08-20 22:13:57 +03:00
|
|
|
, headers: { "Content-Type": "application/json" }
|
|
|
|
}
|
|
|
|
{ json: { hello: world } } :: HttpBinResponse <- fromJson json
|
|
|
|
log world
|
|
|
|
```
|