简体   繁体   中英

How to make and handle POST request

I have a Clojure service:

(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 })))

If I test it using REST client - it works fine:

在此输入图像描述

If I use it from jQuery I have an error:

$.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);
        }
      });

Here is logs from server:

{:link http://www.linux.org.ru/news/internet/12919692}
#object[org.eclipse.jetty.server.HttpInputOverHTTP 0x11724c56 HttpInputOverHTTP@11724c56]

First message from REST client, second from my AJAX jQuery request ?

Where did I make an error? The REST client works fine. So I can propose that the server is correct. Why the server can not parse the request from jQuery ?

Update: I can solve problem by:

(json/read-str (slurp body)

on the server side. In this case I can work with my jQuery request, but can not parse REST Client request.

The ring JSON middleware uses the Content-Type header to detect and parse JSON payloads. Most likely the request from jQuery is either omitting this header, or using a default value, so the request body shows up to your handler as a raw text stream.

From the jQuery docs it looks like the dataType tells jQuery what data type you're expecting in the response . It looks like you want to be setting the contentType parameter to "application/json" .

You must to say to requester you are sending text or json by changing your header response:

(-> (ring-resp/response (str "Ok"))
    (ring-resp/header ("Content-Type" "text/plain"))) 
    ;; or application/json if convenient 

Try This One

 $.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); } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM