I'm trying to create an Http.Request value:
request : Http.Request
request =
{ verb = "POST"
, headers =
[ ( "Origin", "http://elm-lang.org" )
, ( "Access-Control-Request-Method", "POST" )
, ( "Access-Control-Request-Headers", "X-Custom-Header" )
]
, url = url
, body = body
}
The code is embedded in the function below:
tryRegister : Form -> (Result Http.Error JsonProfile -> msg) -> Cmd msg
tryRegister form msg =
let
url =
baseUrl ++ "register"
body =
encodeRegistration form |> Http.jsonBody
request : Http.Request
request =
{ verb = "POST"
, headers =
[ ( "Origin", "http://elm-lang.org" )
, ( "Access-Control-Request-Method", "POST" )
, ( "Access-Control-Request-Headers", "X-Custom-Header" )
]
, url = url
, body = body
}
in
Http.send msg request
I receive the following error:
Type Http.Request has too few arguments. - Expecting 1, but got 0.
What argument is Http.Request missing?
Appendix:
http://package.elm-lang.org/packages/evancz/elm-http/3.0.1/Http
Your appendix link is to an old version of the Http package. The new package is elm-lang/http. The type parameter that Request expects is the type to use in a successful response, which in your case looks like it should be JsonProfile.
The evancz/elm-http package is deprecated, you are probably actually using elm-lang/http so you're looking at the wrong documentation.
To construct a Http.Request using elm-lang/http you need to call the Http.request function and pass it a record describing the request.
http://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#request
Additionally you can't actually set the 'Origin' header for a request from within the browser this means you'll won't need to set any headers at all and can just use the Http.post helper function http://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http#post
Related
I am have some problems passing in the correct headers for my graphql endpoints
The use case in Postman:
call requestToken endpoint to obtain sessionToken value
requestToken response contains Key Value " and Token Value.
For subsequent calls, I set postman headers as:
Key = X_SESSION_TOKEN Value = Token Value
The user case in Karate
1st feature 'requestToken.feature' successfully calls and stores key + tokenValue
2nd feature successfully defines and prints the token value
here is my 2nd request:
Feature: version
Background:
* url 'http://api-dev.markq.com:5000/'
* def myFeature = call read('requestToken.feature')
* def authToken = myFeature.sessionToken
* configure headers = { 'X_SESSION_TOKEN': authToken , 'Content-Type': 'application/json' }
Scenario: get version
Given path 'query'
Given text query =
"""
query {
version
}
"""
And request { query: '#(query)' }
When method POST
Then status 200
And print authToken
And print response
I am not sure I send the headers right. Its coming back 200, but I keep getting a error 'token malformed' in the response message
Any suggestions? New at this, thanks!
Honestly this is hard to answer, a LOT depends on the specific server.
EDIT: most likely it is this change needed, explained here: https://github.com/intuit/karate#embedded-expressions
* configure headers = { 'X_SESSION_TOKEN': '#(authToken)' , 'Content-Type': 'application/json' }
2 things from experience:
should it be X-SESSION-TOKEN
add an Accept: 'application/json' header
And try to hardcode the headers before attempting call etc.
Here is an example that works for me:
* url 'https://graphqlzero.almansi.me/api'
* text query =
"""
{
user(id: 1) {
posts {
data {
id
title
}
}
}
}
"""
* request { query: '#(query)' }
* method post
* status 200
The breakpoint on the local server is triggered only once regardless of the page refreshes.
main =
Navigation.program UrlChange
{ init = init
, view = view
, update = update
, subscriptions = (\_ -> Sub.none)
}
init : Navigation.Location -> ( Model, Cmd Msg )
init location =
( { currentRoute = location
, ...
}
, runtime.bootstrap BootstrapResponse
)
The Explore History window reports that only one message was generated after a page refresh:
BootstrapResponse Ok
Question:
Why isn't my bootstrap request being sent to the server after refreshing the landing page?
Appendix:
bootstrap : (Result Http.Error JsonBootstrap -> msg) -> Cmd msg
bootstrap msg =
let
url =
baseUrl ++ "bootstrap"
request =
Http.get url bootstrapDecoder
in
Http.send msg request
Update:
I tested this on both Chrome and Edge.
I'm trying to build a very simple app that will just output the raw JSON object from an api.
So I want a function that will take a url parameter and ideally return the JSON string.
I have the following code:
decode: String -> String
decode jsonString =
Decode.decodeString jsonString
apiResonse : String -> String
apiResonse url =
let
url = "https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats"
request = Http.get Decode.decodeString url
in
Http.send NewRequest request
But I'm struggling to understand the decoder part of the function. If anyone could help me that would be great.
If you just want to get the HTTP response as a string value, use Http.getString. The example you posted using Http.get assumes the result is in JSON and forces you to decode it to an Elm value.
Here is a modified example of the random cat generator code which just displays a dump of the response JSON instead of a cat picture:
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
in
Http.send NewGif (Http.getString url)
Here is a working example on ellie-app.com
I am new to elm,
I have a login api which returns a JWT token in its hedears
curl http://localhost:4000/api/login?email=bob#example&password=1234
response:
HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8
success
now Im trying to write a function that will send request and return the token from the headers in elm
authUser =
Http.send "http://localhost:4000/api/login?email=bob#example&password=1234"
how do I do this in a simple way?
In order to extract a header from a response, you will have to use Http.request along with the expectStringResponse function, which includes the full response including headers.
The expectStringResponse function takes a Http.Response a value, so we can create a function that accepts a header name and a response, then returns Ok headerValue or Err msg depending on whether the header was found:
extractHeader : String -> Http.Response String -> Result String String
extractHeader name resp =
Dict.get name resp.headers
|> Result.fromMaybe ("header " ++ name ++ " not found")
This could be used by a request builder like so:
getHeader : String -> String -> Http.Request String
getHeader name url =
Http.request
{ method = "GET"
, headers = []
, url = url
, body = Http.emptyBody
, expect = Http.expectStringResponse (extractHeader name)
, timeout = Nothing
, withCredentials = False
}
Here is an example on ellie-app.com which returns the value of content-type as an example. You can substitute "authorization" for your purposes.
May I humbly suggest you look at my elm-jwt library, and the get function there?
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResult
JWT tokens normally need to be sent as a Authorization header and this function helps you create a Request type that can be passed to Http.send or Jwt.send
How to read HTTP response body for a non 200 HTTP status
getJson : String -> String -> Effects Action
getJson url credentials =
Http.send Http.defaultSettings
{ verb = "GET"
, headers = [("Authorization", "Basic " ++ credentials)]
, url = url
, body = Http.empty
}
|> Http.fromJson decodeAccessToken
|> Task.toResult
|> Task.map UpdateAccessTokenFromServer
|> Effects.task
The above promotes the error from
Task.toResult : Task Http.Error a -> Task x (Result Http.Error a)
The value of which becomes
(BadResponse 400 ("Bad Request"))
My server responds with what is wrong with the request as a JSON payload in the response body. Please help me retrieve that from the Task x a into ServerResult below.
type alias ServerResult = { status : Int, message : String }
The Http package (v3.0.0) does not expose an easy way to treat HTTP codes outside of the 200 to 300 range as non-error responses. Looking at the source code, the handleResponse function is looking between the hardcoded 200 to 300 range
However, with a bit of copy and pasting from that Http package source code, you can create a custom function to replace Http.fromJson in order to handle HTTP status codes outside the normal "success" range.
Here's an example of the bare minimum you'll need to copy and paste to create a custom myFromJson function that acts the same as the Http package except for the fact it also treats a 400 as a success:
myFromJson : Json.Decoder a -> Task Http.RawError Http.Response -> Task Http.Error a
myFromJson decoder response =
let decode str =
case Json.decodeString decoder str of
Ok v -> Task.succeed v
Err msg -> Task.fail (Http.UnexpectedPayload msg)
in
Task.mapError promoteError response
`Task.andThen` myHandleResponse decode
myHandleResponse : (String -> Task Http.Error a) -> Http.Response -> Task Http.Error a
myHandleResponse handle response =
if (200 <= response.status && response.status < 300) || response.status == 400 then
case response.value of
Http.Text str ->
handle str
_ ->
Task.fail (Http.UnexpectedPayload "Response body is a blob, expecting a string.")
else
Task.fail (Http.BadResponse response.status response.statusText)
-- copied verbatim from Http package because it was not exposed
promoteError : Http.RawError -> Http.Error
promoteError rawError =
case rawError of
Http.RawTimeout -> Http.Timeout
Http.RawNetworkError -> Http.NetworkError
Again, that code snippet is almost entirely copy and pasted except for that 400 status check. Copying and pasting like that is usually a last resort, but because of the library restrictions, it seems to be one of your only options at this point.