我有一個Express post路由,它根據從DataTables編輯器內聯字段發送給它的數據更新mongo數據庫。到目前爲止這麼好,數據庫正在更新。更新查詢成功執行後,我想再重定向回原始頁面。節點控制檯似乎表明正在調用到源網頁的GET路由,但網頁本身不加載。POST後的節點/ Express重定向
的POST函數的代碼如下:當直接調用
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
的GET路由工作正常,但似乎當這樣調用停止。
我很確定在POST路由中沒有任何東西導致這種情況,因爲當我除掉重定向本身以外的任何東西都會發生同樣的事情。
router.post('/test',function(req,res){
res.redirect('/admin');
});
請幫忙!
還請附上您輸入的樣本。你用'.split()'和'.replace()'做的事情對我來說似乎不太明顯。 – Tomalak
拆分和替換是爲了從DataTables編輯器作爲請求發送的多級JSON對象的完整的狗早餐中獲取所需數據。它可能不夠高雅,但實際上,更新正在發揮作用。正如我上面所說,即使沒有任何重定向不起作用(請參閱編輯的問題) – Drum
不要*在JSON上使用字符串方法。這裏沒有「實用」這個詞的空間。解析。的。 JSON。節點中有一個免費的JSON解析器,使用它 - 這是無痛的,也是正確的做法。 – Tomalak