简体   繁体   English

Node.Js 重定向请求永远挂起

[英]Node.Js redirecting request stays on forever pending

I'm very new to Node.Js and I've been trying to imitate the way for redirecting request that I've seen in an Udemy course.我对 Node.Js 很陌生,我一直在尝试模仿我在 Udemy 课程中看到的重定向请求的方式。 Here I'm trying to redirect my page when the button is clicked and I'm doing exactly the same thing that I've seen in the course but when I click the button, the status code which should turn to 302 stays on pending forever and it doesn't redirect me to the specified URL.在这里,我试图在单击按钮时重定向我的页面,并且我正在做与我在课程中看到的完全相同的事情,但是当我单击按钮时,应该变成 302 的状态代码永远保持等待状态它不会将我重定向到指定的 URL。 here is my code:这是我的代码:

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const url = req.url;
  const method = req.method;
  if (url === "/") {
    res.write("<html>");
    res.write(
      '<body><form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form></body>'
    );
    res.write("</html>");
    return res.end;
  }

  if (url === "/message" && method === "POST") {
    fs.writeFileSync("message.txt", "dummy");
    res.statusCode = 302;
    res.setHeader("Location", "/");
    return res.end;
  }
});

server.listen(3000);

res.end() is a function, try calling it. res.end()是一个 function,尝试调用它。

if (url === "/message" && method === "POST") {
  fs.writeFileSync("message.txt", "dummy");
  res.writeHead(302,{ Location: '/'});
  res.end();
}

you can also do it like this:你也可以这样做:

return res.end()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM