首页 > 解决方案 > 快递中的路由处理程序没有调用任何东西?

问题描述

我制作了一个简单的文本框,可以接受

优酷视频网址

哪个切片它的视频 ID 并使用fetch将数据发送到我的快速服务器。我正在使用 Youtube 数据 API v3

//after clicking button sends data
//input fields are defined already.
const sendData = (event) => {
  event.preventDefault();
  const filterUrl = input2.value.indexOf('&') != -1 ? input2.value.slice(0, input2.value.indexOf('&')) : input2.value;
  const url = new URL(filterUrl).searchParams.get("v");
  fetch('/', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        urlname: url.toString()
      })
    })
    .then(function(res) {
      console.log(res)
    })
    .catch(function(error) {
      console.log(error)
    });
}

这是我的快递处理程序:

//defined routes and PARAMETER variable is globally defined
app.route('/')
  .get((req, res) => {
    res.render('container/index', {
      title: 'Hello User!',
      content: 'Welcome to youtube Comment viewer'
    });
  })
  .post((req, res) => {
    console.log("hello")
    PARAMETER = req.body.urlname;
    console.log(PARAMETER);
    res.redirect('/randomCommentView');
  });


//get request 
app.get('/randomCommentView', (req, res) => {
  console.log("inside");
  Comments(PARAMETER)
    .then((data) => {
      res.render('container/comment', {
        Comment: 'fgfg'
      })
    }).catch(err => {
      if (err) res.status(404).render('container/index', {
        notFound: `Your request couldn't be completed ERR: ${err}`
      })
    })
  console.log(req.body);
});

但是当我提交我的 Youtube 视频网址时,该页面保持在同一条路线上。这是我的输出图像:

在此处输入图像描述

所以看起来路由正在被调用,但网页浏览器中的页面 URL 没有改变。有谁知道这可能的原因。感谢和问候。

标签: javascriptnode.jsexpressroutesfetch

解决方案


由于您使用 javascript 发出请求,因此只有 javascript 会跟随您的重定向。

您可以做的不是从服务器发送重定向,而是发送一个特殊代码,该代码将window.location.href = ...在您的客户端 javascript 代码中触发手动重定向 ( )。


推荐阅读