Send POST request from front-end javascript to back-end node.js - Stack Overflow

In the front-end script, I have a code like this to create the POST requestto the server.var xhr = new

In the front-end script, I have a code like this to create the POST request to the server.

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/visitor/detect/1", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        value: "test"
    }));

Then here is my route in my server

router.post('/visitor/detect/1', (req, res) => {
      console.log(req.body);
      res.redirect('/visitor/login');
});

I'm expecting to redirect the page to /visitor/login after a successful post request, but it didn't. However, it is displaying the req.body.

What is the problem, and what way can I do to successfully send the post request from the front-end and redirect the page to the back-end?

In the front-end script, I have a code like this to create the POST request to the server.

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/visitor/detect/1", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        value: "test"
    }));

Then here is my route in my server

router.post('/visitor/detect/1', (req, res) => {
      console.log(req.body);
      res.redirect('/visitor/login');
});

I'm expecting to redirect the page to /visitor/login after a successful post request, but it didn't. However, it is displaying the req.body.

What is the problem, and what way can I do to successfully send the post request from the front-end and redirect the page to the back-end?

Share Improve this question asked Mar 2, 2022 at 12:16 chacha 1412 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

You cannot redirect with the ajax request the way you are trying to do it. Here is an snippet that does what I think you are trying to do. You might also look into the fetch api instead of using XMLHttpRequest.

On the server:

app.post("/visitor/detect/1", (req, res) => {
  console.log(req.body);
  res.json({ redirectRoute: "/visitor/login" });
});

Client side:

  var xhr = new XMLHttpRequest();
    xhr.open("POST", "/visitor/detect/1", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        value: "test"
    }));

    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var jsonResponse = JSON.parse(xhr.responseText)
            window.location.replace(jsonResponse.redirectRoute)
        }
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745236122a4617902.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信