[英]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.