首页 > 解决方案 > 当服务器可以走两条不同的路线时如何获取客户端?

问题描述

我不确定如何执行此操作,但我有一个发布请求服务器端,它根据查询结果转到两条不同的路由。

app.post('/check', function(req, res) {
    connection.query("select exists (select * from visit WHERE id = ?) as 'res' ",
    id, function(err, result) {
      if (err) throw err;
      if(result[0].res == 0) {
        console.log("Doesn't exist in db.")
        res.redirect(307, '/post'); //goes to /post but after post it doesn't go to db
      }
  else {
    //if data exists update
    console.log("Exists in db.")
    res.redirect(307, '/up');  //goes to up but doesn't go to up.html afterwards
  }
}); 

所以请求在上面有效。在它下面不会更改 Web 浏览器的页面。

app.post('/post', function(req, res) {
    //connects to mysql to update database
    res.redirect('/post.html'); //---when database updates the page doesn't change
});

它在下面也不起作用:

app.post('/up', async function(req, res) {
  console.log("/qrupdate: post timeOut");
  let now = moment().format('MMMM Do YYYY, h:mm:ss a');
  data = req.body;
  let id = data.id.toString();
  connection.query("UPDATE visit SET timeOut = ? WHERE id=?", [now, id],
    function(err, result) {
      if (err) throw err;
    });
    res.redirect('/up.html');  //doesn't change page
});

那么为什么即使重定向了网页也不会改变呢?另外,如果我需要做一个 fetch 客户端,那么 fetch 应该是什么样子?我不知道它是走一条路线还是另一条路线,所以我可以这样做;如果发布请求是这样,更新指定位置的页面,否则更新该位置的页面?我不知道什么是可能的,也不知道它应该是什么样子。

fetch(api_url + '/qrcheck', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json'
  },
  body: qrdata
})
   .then((response) => response.json())
.then((data) => {
  console.log('Success:', data);
  //So here it prints the requests but I guess I wanted to do some kind of if statement
//like if post request was /post then window.location = post.html. Else window.location = up.html
    })
    .catch((error) => {
      console.error('Error:', error);
    });

标签: node.jsexpressfetch-api

解决方案


所以我仍然不知道为什么如果它发布到/check然后/up它不会改变页面,它不会去up.html但如果它不必先通过/check(我假设这与它重定向两次有关,如果有人可以提供更多信息,这将有助于人们知道),但是您可以在获取中使用 if 语句data

fetch(api_url + '/check', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json'
  },
  body: qrdata
})
.then((data) => {
  console.log('Success:', data);
    //I have added two if statements to check the location
    //then the client side is updated to that page
  if (data.url == url + '/up.html') {
    window.location.replace(url + '/up.html');
  }
  if (data.url == url + '/post.html') {
    window.location.replace(url + '/post.html');
  }
})
.catch((error) => {
  console.error('Error:', error);
});

推荐阅读