I am writing a single page application in Elm to interface with a Django backend. The Django Rest Framework provides a CSRF token in a cookie but expects all requests to contain the token in an HTTP header.
Is there a way to declaratively instruct Elm to return the CSRF token as HTTP header with each request? E.g., along the line how I would configure it in JS/Axios:
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
There is an old SO question that implies to manually extract the token from the cookie and then use Http.send
for each request. That would mean to wrap all HTTP request functions by hand.
Using version 2.0.0 of the elm/http library, you would need to use request
in order to provide headers. It's fairly common for an application to use a customized version of these "base" methods that ask for whatever your environment requires.
get httpConfig route tagger decoder =
Http.request
{ method = "GET"
, headers = httpConfig.headers
, url = httpConfig.baseUrl ++ route
, body = Http.emptyBody
, expect = Http.expectJson tagger decoder
, timeout = Nothing
, tracker = Nothing
}
post httpConfig route value tagger decoder =
Http.request
{ method = "POST"
, headers = httpConfig.headers
, url = httpConfig.baseUrl ++ route
, body = Http.stringBody "application/vnd.api+json" (Encode.encode 0 value)
, expect = Http.expectJson tagger decoder
, timeout = Nothing
, tracker = Nothing
}