2017-08-05 117 views
0

我不明白如何發送請求從我的前端與jquery到後端觸發應該搜索數據庫和刪除/更新文檔的功能。我只想按下按鈕並刪除/更新文檔。一切工作正常如果我通過郵遞員提交請求。我是一個有節點的初學者,我找不到解決方案。如何從前端觸發後端節點/快遞功能?

app.js

app.delete('/delete/:id', (req, res) => { 
 
    let id = req.params.id; 
 
    if (!ObjectID.isValid(id)) { 
 
    return res.status(400).send(); 
 
    } 
 
    Blog.findByIdAndRemove(id).then((docs) => { 
 
    res.status(200).send({docs}) 
 
    }).catch((e) => { 
 
    res.status(400) 
 
    }); 
 
}); 
 

 
app.patch('/update/:id', (req, res) => { 
 
    var id = req.params.id 
 
    var update = {autore: req.body.autore} 
 
    if (!ObjectID.isValid(id)) { 
 
    res.status(400).send() 
 
    } Blog.findByIdAndUpdate(id, update, {new: true}).then((docs) => { 
 
     res.send({docs}); 
 
    }).catch((e) => { 
 
    res.status(400) 
 
    }); 
 
});

HTML

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Titolo</title> 
 
    </head> 
 
    <body> 
 
     <button id:"cancella" type="submit">Submit</button 
 

 
    <script src="/js/jquery.js"></script> 
 
    <script src="/js/script.js"></script> 
 
    </body> 
 
</html>

這個script.js文件是否也必須由後端管理?

預先感謝您!

的script.js

$(document).ready(function() { 
 
$('#cancella').on("click", function() { 
 
    $.ajax({ 
 
    url: '/delete/:id', 
 
    type: 'DELETE', 
 
    data: {"_id": 5984f1a8d2c11b0354d1601b}, 
 
    dataType: 'json', 
 
    success: function(data) { 
 
    console.log('Dati cancellati!' + data); 
 
    }}); 
 
}); 
 
});

回答

0

jQuery您在發送idbodynode你在你的query parameters越來越..

你應該改變你的jQuery網址,你不需要發送任何body

$(document).ready(function() { 
$('#cancella').on("click", function() { 
    var baseURL = 'http://localhost' // depending of your config you should set this 
    $.ajax({ 
    url: baseURL + '/delete/' + 5984f1a8d2c11b0354d1601b, 
    type: 'DELETE', 
    success: function(data) { 
    console.log('Dati cancellati!' + data); 
    }}); 
}); 
}); 

這應該做的伎倆

+0

它似乎沒有工作,我的基本URL「http://192.168.0.4:3000」和任何其他ID。看來,瀏覽器不發送任何請求:( – Artax5005

相關問題