如何在 Hunchentoot 或 Clack 中启用 CORS,或者如何添加特定的 header?

How to enable CORS in Hunchentoot or Clack, or how to add a specific header?

问题说明了一切。本教程:https://www.html5rocks.com/en/tutorials/cors/ 说至少要在服务器的响应中添加 Access-Control-Allow-Origin: * header。

我的应用 运行 Hunchentoot,return 不是:

<!-- GET http://127.0.0.1:9000/ -->
<!-- HTTP/1.1 200 OK -->
<!-- Date: Fri, 13 Oct 2017 23:26:58 GMT -->
<!-- Server: Hunchentoot 1.2.37 -->
<!-- Keep-Alive: timeout=20 -->
<!-- Connection: Keep-Alive -->
<!-- Transfer-Encoding: chunked -->
<!-- Content-Type: text/html;charset=utf-8 -->
<!-- Request duration: 0.004275s -->

我查看了 Hunchentoot's doc and its headers.lisp 文件但找不到任何内容 CORS-specific 并且不明白如何简单地添加 header.

有什么帮助吗?谢谢!


编辑:我实际上使用的是 Lucerne 和 Clack。

(in-package :cl-user)
(defpackage lisp-todo
  (:use :cl
        :lucerne)
  (:export :app)
  (:documentation "Main lisp-todo code."))
(in-package :lisp-todo)

添加

(defun change-headers (headers)
  (setf (lack.response:response-headers *response*) headers))

C-c C-c =>

package lack.response does not exist.

或使用 Hunchentoot:

(setf (hunchentoot:header-out "Access-Control-Allow-Origin") "*")

the variable Hunchentoot:*reply* is unbound.

确实这个变量是用def-unbound定义的。


edit2:尝试使用 Ningle

(in-package :cl-user)
(defpackage todobackend-ningle
  (:use :cl))
(in-package :todobackend-ningle)

;; blah blah blah.

(defvar *response* nil "") ;; to try the snippet below

(defun change-headers (headers)
  ;; (setf (lack.response:response-headers *response*) headers)) ;; => the value nil is not of type lack.response:response
  (setf (lack.response:response-headers lack.response:response) headers)) ;; => unbound

(defvar *app* (make-instance 'ningle:<app>))

(change-headers '(:access-control-allow-origin "*"))

(setf (ningle:route *app* "/")
      (lambda (params) ;; is that right ?
           (change-headers '(:access-control-allow-origin "*"))
           "Welcome to ningle!"))

下面是我用 Ningle 做 Clack 的代码,希望对你有帮助:

(defpackage ...
  (:use :cl :ningle))
(in-package ...)

(defun change-headers (headers)
  (setf (lack.response:response-headers *response*) headers))

(defmacro api-route (url method en-tetes &body corps)
  `(setf (ningle:route *app* ,url :method ,method)
     ;; that's why your code doesn't work, you actually have to pass a #'function
     #'(lambda (params)
         (change-headers ,headers)
         ,@corps)))

注意:*response*来自ningle.context,根据文件中的注释,我可能用错了。

这个宏可以用来创建路由并指定headers,像这样:

(api-route
   "/"
   :get
   '(:access-control-allow-origin "*")
   "Welcome!")

请记住,这对于 GET 请求就足够了,但对于其他动词,浏览器将首先点击 OPTIONS。您至少必须回答 headers:

  '(:access-control-allow-methods "POST"          ; or any other verb(s)
    :access-control-allow-origin "*"
    :access-control-allow-headers "content-type")

这段代码来自我的一个小玩具项目。喜欢的可以看看the rest of it,希望能给大家一些思路。这没什么大不了的,可能有更好的方法来做到这一点,但是嘿——它有效。