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

3

问题实际上是您返回的 JSON 对象的内容类型 ( application/vnd.me.org.api+json) 是 Restify 不知道的(因此会产生错误 no formatter found)。

你需要告诉 Restify 你的回复应该如何格式化:

server = restify.createServer({
  formatters : {
    '*/*' : function(req, res, body) { // 'catch-all' formatter
      if (body instanceof Error) { // see text
        body = JSON.stringify({
          code    : body.body.code,
          message : body.body.message
        });
      };
      return body;
    }
  }
});

body instanceof Error也是必需的,因为必须先将其转换为 JSON,然后才能将其发送回客户端。

*/*构造创建了一个“包罗万象”的格式化程序,用于所有 Restify 无法自行处理的 mime 类型(该列表是、application/javascriptapplication/json)。我可以想象在某些情况下,包罗万象的格式化程序可能会带来问题,但这取决于您的确切设置。text/plainapplication/octet-stream

于 2013-04-02T11:22:46.683 回答