[英]How to make and handle POST request
我有一個Clojure服務:
(ns cowl.server
(:use compojure.core)
(:require [ring.adapter.jetty :as jetty]
[ring.middleware.params :as params]
[ring.middleware.json :as wrap-json]
[ring.util.response :refer [response]]
[clojure.data.json :as json]
[cowl.settings :as settings]
[cowl.db :as db]))
(defn set-as-readed [body]
(println body)
(db/set-as-readed settings/db (:link body))
(str "ok"))
(defroutes main-routes
(POST "/api/news/as-read" { body :body } (set-as-readed body)))
(def app
(-> main-routes
wrap-json/wrap-json-response
(wrap-json/wrap-json-body { :keywords? true })))
如果我使用REST客戶端測試它 - 它工作正常:
如果我從jQuery使用它我有一個錯誤:
$.ajax({
url: 'http://localhost:3000/api/news/as-read',
dataType: 'json',
type: 'POST',
data: JSON.stringify( { link: news.link } ),
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.log(error);
}
});
這是來自服務器的日志:
{:link http://www.linux.org.ru/news/internet/12919692}
#object[org.eclipse.jetty.server.HttpInputOverHTTP 0x11724c56 HttpInputOverHTTP@11724c56]
來自REST客戶端的第一條消息,第二條來自我的AJAX jQuery請求?
我在哪里犯了錯誤? REST客戶端工作正常。 所以我可以建議服務器是正確的。 為什么服務器無法解析來自jQuery的請求?
更新:我可以解決問題:
(json/read-str (slurp body)
在服務器端。 在這種情況下,我可以使用我的jQuery請求,但無法解析REST客戶端請求。
環JSON中間件使用Content-Type
標頭來檢測和解析JSON有效負載。 很可能是來自jQuery的請求要么省略此標頭,要么使用默認值,因此請求主體會將您的處理程序顯示為原始文本流。
從jQuery文檔看起來, dataType
告訴jQuery你在響應中期望的數據類型。 看起來您想要將contentType
參數設置為"application/json"
。
您必須通過更改標頭響應向請求者說明您正在發送文本或json:
(-> (ring-resp/response (str "Ok"))
(ring-resp/header ("Content-Type" "text/plain")))
;; or application/json if convenient
試試這一個
$.ajax({ url: 'http://localhost:3000/api/news/as-read', dataType: 'json', type: 'POST', data: { link: news.link }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.log(error); } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.