html - 仅 Express 加载主页

标签 html node.js express fs

我正在努力学习 express 。我正在使用 FS 加载我的 HTML 页面。我通过 google 搜索唯一能找到的就是使用 ASP.NET 而不是 Express。

服务器.js:

var express = require('express');
var path = require('path');
var fs = require('fs');

var app = express();

app.use(require('body-parser').urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname+'/')))

app.get('/', function(a,b,c){
  fs.readFileSync('index.html');
});

app.post('/testaction', function(a,b){
    console.log(a.body.log);
    fs.readFileSync('Logged.html');
});

app.listen(3000);

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
  </head>
  <body>
    <form method="post" action="http://localhost:3000/testaction">
      <h1>Log This:</h1>
      <input type="text" name="log"/>
      <input type="submit", value="Press Me!"/>
    </form>
  </body>
</html>

最佳答案

为了提供文件,您不必使用 fs.示例:

app.get('/', function(req, res, next) {
  res.render('index');
});

如果需要重定向,可以使用:

res.redirect('/staticFile.html');

关于html - 仅 Express 加载主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43377544/

相关文章:

html - CSS 菜单事件/当前链接无法正常工作

php - HTML/PHP/MYSQL - 如何使用 MYSQL 中的 2 个不同字段填充下拉列表

javascript - 表已添加到 MYSQL,但在发布时返回 500

javascript - 轮播内的内容可编辑,导致事件传播

javascript - 如何动态设置 Angular JS 页面的元标签以进行 Facebook 共享?

node.js - 在 NodeJS 中重置变量和异步编程

node.js - Node : illegal access error - using es6 proxies

javascript - frisbyjs 测试失败,因为 get() 未发送 HTTP header

node.js - 如何从 Socket.IO 向数组 (MongoDB) 添加数据? (node.js)

node.js - Express 消息 '!=' 在 Pug 中抛出错误