Expressjs - req.xhr无法识别AJAX

时间:2017-07-25 11:07:24

标签: node.js ajax express request

我的应用程序中有一个操作,用户通过AJAX调用触发DELETE删除他们的帐户,然后重定向到主页并显示一条消息。操作按预期发生,但不显示消息。我无法使用Flash消息,因为我在删除时会破坏会话,因此我决定使用if(req.xhr)并使用视图呈现传递一个对象(如果true,只传递视图false 1}}。但是,我的路线似乎没有从X-Requested-With:XMLHttpRequest识别DELETE并因此传递else声明。谁能指出我为什么会这样?

这是我的路线:

siteRoutes.get('/', function(req, res) {    
    if(req.xhr) {
        console.log("AJAX request")
        res.render('pages/site/index.hbs',{
            successMessage: "Account was successfully deleted."
        });
    } else {
        console.log("Regular request") //Being triggered
        res.render('pages/site/index.hbs');
    }
});

这是我的AJAX:

$.ajax({
     method: 'DELETE',
     url: '/app/settings/account/delete',
     data: { successMessage: "Account was successfully deleted" },
     success: function(){
         window.location.replace('/');
     },
     error: function(error){
         console.log(error);
     }
});

更新

appRoutes.delete('/settings/account/delete', function(req, res){
return 
   ....
.then(function(){
            req.session.destroy();
            req.logout();
    })

1 个答案:

答案 0 :(得分:0)

您的Ajax函数发送方法export function YourRestApi(username1, password1) { fetchlogin(username1, password1); } function fetchlogin(username1, password1) { const details = { username: username1, password: password1, }; const formBody = Object.keys(details).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`).join('&'); fetch('https://*********************', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }, body: formBody, }) .then((response) => response.json()) .then((response) => { console.log('requestAppInstallation success ', response); return response; }) .done(); }

DELETE

因此,您应该将路线方法更改为$.ajax({ method: 'DELETE', url: '/app/settings/account/delete', data: { successMessage: "Account was successfully deleted" }, success: function(){ window.location.replace('/'); }, error: function(error){ console.log(error); } }); ,如下所示:

delete