来自AJAX PUT的数据未被发送到expressjs服务器

时间:2013-09-23 20:15:20

标签: jquery ajax express put

我正在向后端推送一个AJAX“PUT”调用。我似乎无法使用来自AJAX调用的数据获取'req.body'对象。

是否与form.serialize()有关? 有什么建议吗?

路由/ index.js

app.put('/:library/:book/:genre', function(req, res) {
  console.log(req.body.book-name);
  res.send(200, {"youKnow":"putter"});  
});

libraryBookForm.jade

form#create-library-form(action='#', method='post')
      input(name="_method", value="PUT", type="hidden")
      div
        label Book
        input#book-name(type='text', name='book-name', required='required')
      div
        label Gender
        select#book-genre(name='book-genre')
          option(value='scifi') SciFi
          option(value='fantasy') Fantasy
      div
        input(type='submit', id='create-book-submit', value='Create Book')

libraryBookAjax.js

event.preventDefault();
$.ajax({
  url: '/publicLibrary/drawingBook/fantasy'
  type: 'PUT',
  contentType: 'application/json: charset=utf-8',
  dataType: 'json',
  data: form.serialize()
}).done(function(msg) {
  alert("put success: " + msg);
}).fail(function(msg) {
  console.log("failure: " + msg);
});

1 个答案:

答案 0 :(得分:2)

contentType不应该是上面所述的。

将其更改为
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
产生正确的结果。