Ajax删除请求& Node / Express中的响应 - 在调用方法后如何使用GET方法重定向?

时间:2016-10-07 21:26:46

标签: javascript ajax node.js express

我是AJAX和Node的新手,并不确定如何处理: 我有一个DELETE ajax调用,从数据库中删除行后我想重定向回相同的路由,但使用GET方法。我相信我也可以从前端脚本重定向页面,我不确定哪个是正确的策略。任何帮助表示赞赏!

前端js制作ajax调用script.js

  $('.deleteRepository').on('click', function(event) {    
    event.stopImmediatePropagation();
    var username = $(this).attr('username');
    var repoName = $(this).attr('repoName');
    var oReq = new XMLHttpRequest();
    oReq.open("delete", "/user/"+username+'/'+repoName);
    oReq.send();
  });

myRoute.js

router.route('/:username/:repository')
    .delete(function(req, res) {
      console.log('\n\nDelete method called\n\n');
      let username = req.params.username;
      let repoName = req.params.repository;

      deleteRepositoryFromUser(req, res)
        .then(function() {
          console.log('deleted, now redirect');
          //I want to redirect to this page using GET, but logs DELETE
          //I also want to redirect to /user/TonyStark/Favorites
          res.redirect(200, '/user/'+username+'/Favorites'); 
        })

控制台

GET /user/TonyStark/delMe 200 114.702 ms - 4075
...    

Delete method called


deleteRepositoryFromUser()
repoName: delMe
username: TonyStark
deleted, now redirect
DELETE /user/TonyStark/delMe 200 4.568 ms - 44 //how can I make GET?
//why is it not going to /user/TonyStark/Favorites?

2 个答案:

答案 0 :(得分:0)

此行错误res.redirect(200, '/user/'+username+'/Favorites');。您无法使用代码200重定向。您必须使用301或302重定向。请在此处查看http代码:https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

答案 1 :(得分:0)

您还可以在重定向之前手动将HTTP方法设置为GET。
myRoute.js

router.route('/:username/:repository')
.delete(function(req, res) {
  console.log('\n\nDelete method called\n\n');
  let username = req.params.username;
  let repoName = req.params.repository;

  deleteRepositoryFromUser(req, res)
    .then(function() {
      console.log('deleted, now redirect');

      //Explicitly set the HTTP method to GET
      req.method = "GET"

      res.redirect(200, '/user/'+username+'/Favorites'); 
    })