简体   繁体   中英

node.js, page not redirecting - statusCode, setHeader

It should redirect back to the "/" root url, but somehow it's not working properly. it gives the 302 confirmation, but it wont get there

const fs = require("fs");

function requestHandler(req, res) {
  const url = req.url;
  const method = req.method;
  if (url === "/") {
    res.write("<html>");
    res.write("<head><title> Minha primeira página! </title></head>");
    res.write(
      "<body><form action='/message' method='POST'><input type='text' name ='message'><button type='submit'>Enviar</button></form></body>"
    );
    res.write("</html>");
    return res.end();
  }
  //console.log(req.url, req.method, req.headers);
  if (url === "/message" && method === "POST") {
    const body = [];
    req.on("data", (chunk) => {
      console.log(chunk);
      body.push(chunk);
    });
    req.on("end", () => {
      const parsedBody = Buffer.concat(body).toString();
      const message = parsedBody.split("=")[1];
      fs.writeFile("message.txt", message, (err) => {});
    });
    res.statusCode = 302;
    res.setHeader = ("Location", "/");
    return res.end();
  }
}

Redirect to "/" after solving /message

You can use redirect to go to the home page like

res.redirect('/');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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