修改online example,我具有以下代码,该代码允许对此Racket网络服务器发出http请求;
#lang racket
(require web-server/servlet)
(require web-server/servlet-env)
(define (http-response content)
(response/full
200 ; HTTP response code.
#"OK" ; HTTP response message.
(current-seconds) ; Timestamp.
TEXT/HTML-MIME-TYPE ; MIME type for content.
'() ; Additional HTTP headers.
(list ; Content (in bytes) to send to the browser.
(string->bytes/utf-8 content))))
(define (show-time-page request)
(http-response (number->string (current-seconds))))
(define (greeting-page request)
(http-response (list-ref '("Hi" "Hello") (random 2))))
(define get-data ...)
;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
(dispatch-rules
[("time") show-time-page]
[("hello") greeting-page] ; Notice this line.
[else (error "There is no procedure to handle the url.")]))
(define (request-handler request)
(dispatch request))
;; Start the server.
(serve/servlet
request-handler
#:launch-browser? #f
#:quit? #f
#:listen-ip "127.0.0.1"
#:port 8001
#:servlet-regexp #rx"")
如何更改以上代码,以使其能够通过http请求接收发布到Racket网络服务器的数据(例如字符串)并在控制台中显示?请您帮忙?
答案 0 :(得分:0)
为POST
请求定义一个请求处理程序。让它从request
中提取发布的数据:
(define (example-post request)
(define data (request-post-data/raw request))
(define str (format "got post data: ~v" data))
(displayln str)
(http-response str))
将处理程序添加到dispatch-rules
。确保指定它正在处理POST
(不是默认的GET
)请求:
;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
(dispatch-rules
[("time") show-time-page]
[("hello") greeting-page]
[("example-post") #:method "post" example-post] ; <=== NEW
[else (error "There is no procedure to handle the url.")]))
现在,如果需要,在外壳中
curl --data "hi" http://127.0.0.1:8001/example-post
它将显示响应数据got post data: #"hi"
---和Racket控制台一样。