如何用expressjs“PUT”一个ajax调用

时间:2013-09-23 12:00:57

标签: jquery ajax forms express put

我有一个表单,在提交后处理AJAX调用 在express.js中,为了使用其他HTTP动词,表单必须具有
<input type="hidden" name="_method" value="put">

AJAX调用已type: "PUT",当它发送到服务器端时,我不断收到404Cannot PUT

对于PUT请求,AJAX或表单是否需要成功提交其他内容? 有什么建议吗?

routes / index.js

app.put('/:library/:book/:genre/', function(req, res) {
  console.log(req.params.genre);
  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);
    });

我还在AJAX请求中尝试了type: "POST"。在这种情况下,POST请求会在路由中发送并执行,而不是app.put

1 个答案:

答案 0 :(得分:1)

变化:

app.put('/:library/:book/:genre/', function(req, res) {

为:

app.put('/:library/:book/:genre', function(req, res) {

尾部斜杠导致404错误,因为您的AJAX调用的URL中没有。