[英]Cannot redirect to new page with NodeJS (Express)
很长一段时间以来,我一直在尝试弄清楚如何使用 NodeJS 和 Express 在单击按钮时将用户简单地重定向到新页面。 按下一页(index.html)的“下一页”按钮的结果是错误Cannot GET /nextpage.html
。 当我打开控制台时,我看到服务器以 404 错误响应。 index.html 和 nextpage.html 都存储在“views”文件夹中。 这是我的 index.html、server.js 和 client.js:
索引.html
<.DOCTYPE html> <html> <p>Home</p> <a href="nextpage.html" id="button">Next page</a> </html>
服务器.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);
});
客户端.js
$(function name() {
$('#button').click(function() {
$.get({url: '/next'}, function(data) {
console.log("Next page requested.");
});
});
});
你在 HTML 做错了。 在 HTML 中,您的锚标记 href 是“nextpage.html”,这不是有效路线。 所以它会抛出404。
点击锚标签正在做两件事
锚点重定向的默认性质将 go 到 'http://localhost:8080/nextpage.html'
你可以像下面这样解决这个问题。
<!DOCTYPE html>
<html>
<p>Home</p>
<a href="/next" id="button">Next page</a>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.