0

次のように使用して、node.js/ restifyの RESTful API で Accept ヘッダーを適切に処理しようとしてWrongAcceptErrorいます。

var restify = require('restify')
  ; server = restify.createServer()

// Write some content as JSON together with appropriate HTTP headers. 
function respond(status,response,contentType,content)
{ var json = JSON.stringify(content)
; response.writeHead(status,
  { 'Content-Type': contentType
  , 'Content-Encoding': 'UTF-8'
  , 'Content-Length': Buffer.byteLength(json,'utf-8')
  })
; response.write(json)
; response.end()
}

server.get('/api',function(request,response,next)
{ var contentType = "application/vnd.me.org.api+json"
; var properContentType = request.accepts(contentType)
; if (properContentType!=contentType)
  { return next(new restify.WrongAcceptError("Only provides "+contentType)) }
  respond(200,response,contentType,
  { "uri": "http://me.org/api"
  , "users": "/users"
  , "teams": "/teams"
  })
  ; return next()
});

server.listen(8080, function(){});

クライアントが正しいAcceptヘッダーを提供するか、ここに示すようにヘッダーを提供しない場合、これは正常に機能します。

$ curl -is http://localhost:8080/api
HTTP/1.1 200 OK
Content-Type: application/vnd.me.org.api+json
Content-Encoding: UTF-8
Content-Length: 61
Date: Tue, 02 Apr 2013 10:19:45 GMT
Connection: keep-alive

{"uri":"http://me.org/api","users":"/users","teams":"/teams"}

問題は、クライアント実際に間違ったAcceptヘッダーを提供した場合、サーバーがエラー メッセージを送信しないことです。

$ curl -is http://localhost:8080/api -H 'Accept: application/vnd.me.org.users+json'
HTTP/1.1 500 Internal Server Error
Date: Tue, 02 Apr 2013 10:27:23 GMT
Connection: keep-alive
Transfer-Encoding: chunked

クライアントは、次のように JSON 形式のエラー メッセージを理解すると想定されていないためです。

$ curl -is http://localhost:8080/api -H 'Accept: application/json'
HTTP/1.1 406 Not Acceptable
Content-Type: application/json
Content-Length: 80
Date: Tue, 02 Apr 2013 10:30:28 GMT
Connection: keep-alive

{"code":"WrongAccept","message":"Only provides application/vnd.me.org.api+json"}

したがって、私の質問は、どのようにしてrestifyに正しいエラー ステータス コードと本文を強制的に送り返すか、または間違ったことをしているのですか?

4

1 に答える 1