A library taking advantage of aff
to enable pain-free asynchronous AJAX requests and response handling.
Install affjax
with Spago:
spago install affjax
If you are using affjax
in a Node.js setting you will also need to install an additional NPM dependency:
npm install xhr2
You can construct requests with the request
function:
module Main where
import Prelude
import Affjax as AX
import Affjax.ResponseFormat as ResponseFormat
import Data.Argonaut.Core (stringify, fromString)
import Data.Either (Either(..))
import Data.HTTP.Method (Method(..))
import Effect.Aff (launchAff)
import Effect.Class.Console (log)
main = void $ launchAff $ do
result <- AX.request (AX.defaultRequest { url = "/api", method = Left GET, responseFormat = ResponseFormat.json })
case result of
Left err -> log $ "GET /api response failed to decode: " <> AX.printError err
Right response -> log $ "GET /api response: " <> stringify response.body
(defaultRequest
is a record value that has all the required fields pre-set for convenient overriding when making a request.)
There are also a number of helpers for common get
, post
, put
, delete
, and patch
cases:
import Affjax.RequestBody as RequestBody
import Data.Maybe (Maybe(..))
import Effect.Aff (launchAff_)
main = launchAff_ do
result1 <- AX.get ResponseFormat.json "/api"
case result1 of
Left err -> log $ "GET /api response failed to decode: " <> AX.printError err
Right response -> log $ "GET /api response: " <> stringify response.body
result2 <- AX.post ResponseFormat.json "/api" (Just (RequestBody.json (fromString "test")))
case result2 of
Left err -> log $ "POST /api response failed to decode: " <> AX.printError err
Right response -> log $ "POST /api response: " <> stringify response.body
affjax
documentation is stored in a few places:
- Module documentation is published on Pursuit.
- Written documentation is kept in the docs directory.
- Usage examples can be found in the test suite.
If you get stuck, there are several ways to get help:
- Open an issue if you have encountered a bug or problem.
- Search or start a thread on the PureScript Discourse if you have general questions. You can also ask questions in the
#purescript
and#purescript-beginners
channels on the Functional Programming Slack (invite link).
You can contribute to affjax
in several ways:
-
If you encounter a problem or have a question, please open an issue. We'll do our best to work with you to resolve or answer it.
-
If you would like to contribute code, tests, or documentation, please read the contributor guide. It's a short, helpful introduction to contributing to this library, including development instructions.
-
If you have written a library, tutorial, guide, or other resource based on this package, please share it on the PureScript Discourse! Writing libraries and learning resources are a great way to help this library succeed.