javascript - Node.js 不从“公共/视图”路由呈现 html 页面
问题描述
在从 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>
在您的页面而不是那个输入元素中?
推荐阅读
- java - Java ASM“类型顶部(当前帧,locals [0])不可分配给引用类型”
- python - Python:定义单独的分箱
- c# - 列出子网 C# .net 核心中的 IP 地址
- r - 如何找到回归线中的交点
- bash - 在bash脚本中使用一个命令删除一定数量的变量(不是全部不是一个)
- asp.net - 如何在 asp.net 中发送图像文件和其他参数?
- ms-access - 如何在 Access 中将组合框作为参数传递?
- terraform - 在 Terraform 中加入两个字符串
- linux - 符号查找错误(如何将共享库与另一个库链接)
- powershell - 在客户端机器上寻找 pograms