【问题标题】:Cannot redirect to new page with NodeJS (Express)无法使用 NodeJS (Express) 重定向到新页面
【发布时间】:2020-12-29 22:42:34
【问题描述】:

很长一段时间以来,我一直在尝试弄清楚如何使用 NodeJS 和 Express 在单击按钮时将用户简单地重定向到新页面。按下一页(index.html)的“下一页”按钮的结果是错误Cannot GET /nextpage.html。当我打开控制台时,我看到服务器以 404 错误响应。 index.html 和 nextpage.html 都存储在“views”文件夹中。这是我的 index.html、server.js 和 client.js:

index.html

<!DOCTYPE html>
<html>
    <p>Home</p>
    <a href="nextpage.html" id="button">Next page</a>
</html>

server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const http = require('http')

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static('public'));

app.get("/", function (request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

app.get("/next", function (request, response) {
    response.sendFile(__dirname + '/views/nextpage.html');
});

var listener = app.listen('8080', function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

client.js

$(function name() {
  
    $('#button').click(function() {
      $.get({url: '/next'}, function(data) {
          console.log("Next page requested.");
      });
    });
});

【问题讨论】:

  • nextpage.html 视图的路径是 /next
  • @tkausl 更正了我的帖子,更新获取请求后我仍然收到相同的错误。
  • 我不认为$.get 做了您认为它所做的事情 - 您可能需要查看其documentation page 上的功能摘要。您的函数所做的只是检索在该端点提供的内容,而不对它们做任何事情。这完全不同于允许a 标签将用户的浏览器移动到适当的页面。在这种情况下,不要尝试处理 click 事件 - 只需正确设置您的 a 标签的 href 属性并允许跟随链接:&lt;a href="/next" id="button"&gt;Next page&lt;/a&gt;

标签: javascript html node.js express


【解决方案1】:

你在 HTML 中做错了。 在 HTML 中,您的锚标记 href 是“nextpage.html”,这不是有效路线。所以它会抛出 404。

点击锚标签做了两件事

  1. 触发Js onclick事件。
  2. 默认性质(转到 href 值)

锚点重定向的默认性质将转到“http://localhost:8080/nextpage.html”

你可以像下面这样解决这个问题。

<!DOCTYPE html>
<html>
    <p>Home</p>
    <a href="/next" id="button">Next page</a>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2017-11-02
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多