带标题的自定义http post请求

时间:2013-12-30 13:57:51

标签: elm

我想使用json作为有效负载来发出Http POST请求。我无法使它发挥作用。

使用curl我会这样做(实际上,我测试了它并且它有效):

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

使用@request包含要发送的json对象的文件。

我首先尝试使用Http.request,但它提出了一个奇怪的请求。然后我尝试使用Http.post来查看它是否有效。然后请求很好,但Content-type不是json。 此外,在这两种情况下我都没有回应(这可能是由于服务器没有发送任何东西,但我无法验证它。)

要知道我使用我最喜欢的浏览器的开发人员工具栏进行了检查;)

使用Http.request

虽然我想使用POST:

,但它正在使用OPTIONS
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
-}

使用Http.post

它使用text / plain虽然我想使用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"
}
-}

那么,如何使用json有效负载发送POST请求?

1 个答案:

答案 0 :(得分:3)

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

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