【问题标题】:How to manage the redirection in express.js?如何管理 express.js 中的重定向?
【发布时间】:2021-07-06 02:31:30
【问题描述】:

我知道有很多类似的问题,但我找不到任何解决我的问题的方法。

我认为问题在于没有获取 product.html,并且我认为重定向到 product.html 也存在问题。

product.html

<!DOCTYPE html>
<html>
  <head>
    <title>Product</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <form id="product" action="/information" method="POST">
      <label for="product_id">Enter product ID: </label>
      <input id="product_id" name="product_id" type="text" required />
      <input type="submit" />
    </form>
  </body>
</html>

index.js

const express = require("express");

// load data
const products = require("./data.json");

const app = express();

// static files
app.use(express.static("public"));

// form middleware
app.use(express.urlencoded({ extended: true }));

app.post("/information", (req, res) => {
  // ES6 deconstruction syntax, get user input
  const { product_id } = req.body;

  // search product array
  const product = products.find((product) => product.Product_ID === product_id);
  if (product) res.json(product);
  else res.send("product not found");
});

// redirect all GET requests to product form
app.get("*", (req, res) => {
  res.redirect("/product.html");
});

app.listen(8000,console.log(`App listening at http://localhost:8000`));

当我像上面那样运行代码时,我收到以下错误:页面没有正确重定向

(Cookie 和缓存已删除)。我什至用 node.js 服务器尝试了另一个项目,并且 Firefox 中的 localhost 工作。

当我发出重定向命令时,我收到此错误:Cannot GET /

当我在重定向中使用“/”而不是“*”时,会出现此错误:Cannot GET /product.html

我不明白为什么它没有得到 product.html 以及为什么重定向不能正常工作。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    要为每个端点渲染product.html,你可以使用sendFile而不是redirect,你需要使用path模块,它是解析html文件路径的核心模块:

     const path = require('path');
     //your code
     
     app.get('*', (req, res)=> {
          //note that product.html file is in the same directory or you specify    
          //its relative path
          res.sendFile(path.resolve(__dirname, 'product.html'))
     })
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多