2015-10-13 46 views
0

我試圖用NodeJS,Express和Mongo製作我的第一個REST API。我已經掌握了大部分代碼 - 我可以使用GET從數據庫獲取數據,並使用POST寫入數據。但是,由於某種原因,POST回調中的響應參數似乎完全被忽略。我試過調用res.render([一個工作模板]),res.end(),res.send()等,並且代碼似乎跳過了響應,就像它不在那裏。沒有錯誤,只是沒有做任何事情。我還嘗試將POST URI更改爲其他內容,例如/ api/projectsave,以防萬一這些路由互相干擾,但這並沒有幫助。ExpressJS:響應在POST後被忽略

編輯:如果我切換到res.json(),JQuery代碼中的Success回調確實會運行。 (感謝@Molda。)但是,原始問題仍然存在,因爲響應對象不會使用res.render()渲染任何東西。這是爲什麼?

下面是相關的代碼(在我的API控制器):

app.get('/api/project/:id', function(req, res) { 
    Project.find({id: req.params.id}, function(err, projects) { 
     if (err) throw err; 
     if (projects.length > 0) { 
      res.json(projects); 
     } else { 
      res.render('form'); 
     } 
    }); 
}); 

app.post('/api/project', jsonParser, function(req, res, next) { 
    res.render('index'); // Here's the line that doesn't do anything. 
    console.log("Body: " + util.inspect(req.body, false, null)); // This line gets run. 
    var item = Project(req.body); 
    item.save(function(err) { 
     if (err) throw err; // And this save to the db works fine. 
     console.log('Project saved with id ' + req.body.id + '.'); 
     res.render('index'); // Doesn't work down here, either. 
    }) 
}); 

app.get('/api/project', function(req, res) { 
    res.render('form'); 
}); 

和形式(這是一個翡翠模板,但這裏的渲染HTML):

<form id="form" name="add-project" method="POST" action="/api/project"> 
    <div class="input"> 
     <label for="id">ID</label> 
     <input type="text" name="id" id="id"> 
    </div> 
    <div class="input"> 
     <label for="name">Name</label> 
     <input type="text" name="name" id="name"> 
    </div> 
    <div class="input"> 
     <label for="desc">Description</label> 
     <input type="text" name="desc" id="desc"> 
    </div> 
    <div class="actions"> 
     <input type="submit" value="Add Project"> 
    </div> 
</form> 
<script> 
    $.fn.serializeObject = function() 
    { 
     var o = {}; 
     var a = this.serializeArray(); 
     $.each(a, function() { 
      if (o[this.name]) { 
       if (!o[this.name].push) { 
        o[this.name] = [o[this.name]]; 
       } 
       o[this.name].push(this.value || ''); 
      } else { 
       o[this.name] = this.value || ''; 
      } 
     }); 
     return o; 
    }; 
    $("form").submit(function(event) { 
     event.preventDefault(); 
     var jsonData = JSON.stringify($(this).serializeObject()); 
     $.ajax({ 
      type: "POST", 
      url: '/api/project', 
      contentType: 'application/json', 
      dataType: 'json', 
      data: jsonData, 
      success: function(data) { 
       // This callback does successfully run 
       alert("Success: " + data); 
      }, 
      failure: function(err) { 
       alert("Failed: " + err); 
      } 
     }); 
    }); 
</script> 
+0

你可以試試res.json({status:'ok'}); ?你的ajax期望數據類型json,所以它可能會忽略響應,如果它不是json – Molda

+0

我給它一個鏡頭,但沒有幫助。 – user2684124

+0

你能告訴我jsonParser變量嗎? –

回答

0

是它到客戶端重定向下一個POST?

是的。

根據評論,您將從端點獲得適當的呈現頁面。這是一個正確的行爲。你只需要在頁面上的某處插入響應html。