The previous section describes how noir can easily create a web app. However, in my actual project, only rest API development is required, and the page is handed over to HTML and JavaScript, noir is not required to render the webpage in the background.
Similarly, you do not need to restart the program. Create a rest directory under the src directory, which contains a test. CLJ file:
$ tree.├── models├── rest│ └── test.clj├── server.clj└── views ├── common.clj └── welcome.clj
The content of the test. CLJ file is as follows:
(ns my-website.rest.test (:require [my-website.views.common :as common] [noir.content.getting-started]) (:use [noir.core :only [defpage]]))(defpage "/rest/get" [] (common/layout [:p "get"]))
Add a row to the Serer. CLJ file:
(server/load-views-ns 'my-website.rest.test)
Note that in the namespace my-website.rest.test, rest corresponds to the rest directory, and test corresponds to the test. CLJ file.
Then access http: // localhost: 8080/rest/get through the browser
The returned result is a get string. This simplest rest API already exists.
The defpage macro defines the URL routing. By default, it processes http get requests.
Document reference: http://www.webnoir.org/autodoc/1.3.0/noir.core.html#var-defpage
(defpage & args)Adds a route to the server whose content is the the result of evaluating the body.The function created is passed the params of the request and the destruct param allowsyou to destructure that meaningfully for use in the body.There are several supported forms:(defpage "/foo/:id" {id :id}) an unnamed route(defpage [:post "/foo/:id"] {id :id}) a route that responds to POST(defpage foo "/foo:id" {id :id}) a named route(defpage foo [:post "/foo/:id"] {id :id})The default method is GET.
Since we do not need to render the webpage, now we can simplify the code of the test. CLJ file:
(ns my-website.rest.test (:require [noir.content.getting-started]) (:use [noir.core :only [defpage]]))(defpage "/rest/get" [] "get")
Now, the usage of views. Common is removed. Explanation:
1. The first parameter "/rest/get" is the URL of this rest API.
2. The second parameter [] is the HTTP request parameter, which is not used currently.
3. The third parameter "get" is the response content of HTTP response.
Now we will demonstrate how to obtain the parameters of an http get request, for example, entering http: // localhost: 8080/rest/freebird in the browser.
Freebird is a parameter. The code for modifying test. CLJ is as follows:
(defpage "/rest/:id" {:keys [id]} (str "user id: " id))
The second parameter binds the ID of the first parameter to the ID,
The third parameter uses the value of ID to form a response string.
Last return:
User ID: freebird
You can also easily process post requests. For more information, see:
Http://www.webnoir.org/tutorials/routes/