如何使用 Express return 格式良好的 201?

How can I return a well formatted 201 with Express?

我正在尝试使用 ember-cli 使用 DS.RESTAdapter 构建 todoMVC 并表达以模拟调用。我遇到的问题是,当我尝试保存新的待办事项时,我在控制台中看到此错误:

SyntaxError: Unexpected end of input
    at Object.parse (native)
    at jQuery.parseJSON (http://localhost:4200/assets/vendor.js:8717:22)
    at ajaxConvert (http://localhost:4200/assets/vendor.js:9043:19)
    at done (http://localhost:4200/assets/vendor.js:9461:15)
    at XMLHttpRequest.jQuery.ajaxTransport.send.callback (http://localhost:4200/assets/vendor.js:9915:8)

我很确定问题是当我在新创建的模型上调用 save() 时,它正在发送一个 post 请求到/快递正在回复这个:

 todosRouter.post('/', function(req, res) {
    res.status(201).end();
  });

这是 Ember 中创建待办事项的创建操作:

actions:
    createTodo: ->
      return unless title = @get('newTitle')?.trim()

      @set('newTitle', '')
      @store.createRecord('todo',
        title: title
        isCompleted: false
      ).save()

如有任何帮助,我们将不胜感激。我是新手,不确定为什么 jquery 不喜欢它返回的 201。

问题是它试图 parseJSON 空白响应。它实际上在做 jQuery.parseJSON('') - 如果你尝试 运行 它确实会产生错误。

要解决它,您可以 return 任何可以解析为 JSON 的字符串 - 例如字符串 null 或空引号 "".

todosRouter.post('/', function(req, res) {
  res.send('null');
  res.status(201).end();
});

todosRouter.post('/', function(req, res) {
  res.send('""');
  res.status(201).end();
});