[英]Node.js not rendering html page from 'public/views' route
从index.html执行xml http请求后,我试图呈现一些html,但是服务器未呈现我的html页面,即使日志似乎工作正常:
<input type="button" id="response_2" value="No, let me create one :0" class="button" style="width: 100%; height: 100%" onclick="createAccount()">
这是在index.html中找到的按钮
function createAccount() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/createAccount");
xhttp.send();
}
这是javascript函数。 也可以在index.html文件中找到,该文件在按下“ response_2”按钮时执行
var express = require('express');
var app = express();
var http = require('http');
var port = 3000;
var bodyParser = require('body-parser');
var httpServer = http.createServer(app);
httpServer.listen(5500);
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/', function (req, res) {
console.log("someone here...");
res.render('index.html');
});
app.get('/createAccount', function (req, res) {
console.log("here!");
res.render('createAccount.html');
});
app.get('/login', function (req, res) {
res.render('login.html');
});
app.get('/forgotCredentials', function (req, res) {
res.render('forgotCredentials.html');
});
这是node.js服务器的配置
您的密码
app.get('/createAccount', function (req, res) {
console.log("here!");
res.render('createAccount.html');
});
这样可以确保当有人在其浏览器中访问/createAccount
URL时,他们将看到您告诉服务器返回的页面。 您的createAccount()
函数不会在浏览器中打开此URL,它仅发出呈现该页面的请求,因此服务器将返回该页面,但您实际上从未访问过该页面。
你为什么不只用
<a href='/createAccount'>
<button>No, let me create one :0</button>
</a>
在您的页面中,而不是该输入元素中?
在我看来,您缺少一些代码。
在您的客户端示例中,您具有createAccount
函数,该函数将XMLHTTPRequest
激发到服务器。
function createAccount() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/createAccount");
xhttp.send();
}
但是它随后错过了该部分应如何处理请求的response
。 像下面看到的那样,向xhttp
实例添加onreadystatechange
方法。
function createAccount() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(xhttp.readyState === 4 && xhttp.status === 200) {
console.log(xhttp.responseText);
}
}
xhttp.open("GET", "/createAccount");
xhttp.send();
}
每当请求的readyState
更改时,将调用onreadystatechange
。 如此处有关MDN所述。 。 在函数中,您可以控制必须执行的结果。
据我从您的代码可以看出console.log(xhttp.responseText);
应该将createAccount.html
页面输出为字符串。
我的猜测是,您应该只使用链接的href
导航到/createAccount
。
<a href="/createAccount" title="Create account">Create account</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.