0

I would like to make a Http POST request using json as a payload. I can't make it work.

With curl I would do like this (in fact, I tested it and it works):

curl -X POST -d @request http://localhost/jsonrpc --header "Content-Type:application/json"

With @request a file containing the json object to send.

I tried first with Http.request but it's making a weird request. I then tried with Http.post just to see if it works. The request then is fine but the Content-type is not json. Furthermore, in both case I have no response (this may be due to the server not sending anything but I can't verify it).

To know that I checked with my favorite browser's developer toolbar ;)

Using Http.request

It's using OPTIONS although I would like to use POST:

sendJson : Json.JsonValue -> Http.Request String
sendJson json = Http.request "POST" "http://localhost/jsonrpc" ( Json.toString " " json ) [("Content-Type", "application/json")]

{-
Request URL:http://localhost/jsonrpc
Request Method:OPTIONS
Status Code:200 OK

Request Headers:
OPTIONS /jsonrpc HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: POST
Origin: http://localhost:8000
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:8000/MyMovies.elm
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2

HTTP/1.1 200 OK
Connection: close
Content-Length: 157677
Content-Type: application/json
Date: Mon, 30 Dec 2013 11:43:44 GMT
-}

Using Http.post

It's using text/plain although I would like to use application/json:

sendJson json = Http.post "http://localhost/jsonrpc" ( Json.toString " " json )

{-
Request URL:http://localhost/jsonrpc

Request Headers:
POST http://localhost/jsonrpc HTTP/1.1
Cache-Control: max-age=0
Origin: http://localhost:8000
Referer: http://localhost:8000/MyMovies.elm
Content-Type: text/plain;charset=UTF-8

Request payload:
{
 "params": {
  "sort": {
   "order": "ascending",
   "method": "label",
   "ignorearticle": true
  },
  "properties": [
   "art",
   "rating",
   "thumbnail",
   "playcount",
   "file"
  ]
 },
 "method": "VideoLibrary.GetMovies",
 "jsonrpc": "2.0"
}
-}

So, how can I send a POST request with a json payload ?

4

1 回答 1

3

答案在这里:https ://github.com/evancz/Elm/issues/426

TL;DR:这是由CORS引起的正常行为。

于 2014-03-01T00:47:07.823 回答