CORS 开始有点煎熬我的大脑。现在一切都很好,除了一种方法。我正在构建一个应用程序,前端带有主干,后端带有 node.js/restify。server.coffee
看起来像这样:
server.get '/todos', todos.find_all
server.get '/todos/:id', todos.find_by_id
server.del '/todos/:id', todos.delete
但是,每当主干中的模型调用destroy
时,我都会收到这个相当烦人的错误:
MLHttpRequest cannot load http://localhost:8080/todos/. Method DELETE is not allowed by Access-Control-Allow-Methods.
我读了一点,并使用 restify 完成了以下操作:
unknownMethodHandler = (request, response) ->
if(request.method.toLowerCase() == 'options')
allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version']
if(response.methods.indexOf('OPTIONS') == -1) then response.methods.push('OPTIONS')
response.header 'Access-Control-Allow-Credentials', true
response.header 'Access-Control-Allow-Headers', allowHeaders.join(', ')
response.header 'Access-Control-Allow-Methods', ['GET', 'DELETE', 'TEST!']
response.header 'Access-Control-Allow-Origin', request.headers.origin
response.send 204
else
response.send new restify.MethodNotAllowedError()
server.on 'MethodNotAllowed', unknownMethodHandler
但即便如此,我还是把它作为响应头:
HTTP/1.1 204 No Content
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: X-Api-Version, X-Request-Id, X-Response-Time
Connection: Keep-Alive
Date: Mon, 04 Feb 2013 12:24:25 GMT
Server: restify
X-Request-Id: fbd4e15a-a22e-48b6-bf5c-a46b94926748
X-Response-Time: 0
我只是不明白我做错了什么!