2017-04-12 85 views
-2

我不是在谈论一个Button标签。我正在谈论提交类型的输入标签。我正在使用fs来加载当前页面。我试图学习快递。如何在Express中按下提交按钮时打开页面?

Server.js:

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

var app = express(); 

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

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

app.post('/testaction', function(a,b){ 
    console.log(a.body.log); 
    fs.readFileSync('public/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> 
+0

你能分享一些代码,这将有助于澄清你想要做什么?这听起来像是当客户提交你的表单时,你试图将特定的静态页面发送回客户端,以响应特定的POST请求。 –

回答

0

基本上你并不真正需要的FS在这里。

为例app.get()需要2个参数:你想要处理的url和一个带有2或3个参数的回调。

通常我们这样使用它:app.get("/",(req,res)=>{});(req = request,and res = response)。

响应具有发送文件的方法:http://expressjs.com/fr/4x/api.html#res.sendFile

现在对于你的问题,你可以管理这个作为一个Ajax请求:

  • index.html中进行POST Ajax请求/testaction
  • 在server.js只是返回一个状态的app.post
  • 创建像app.get("/test",(req,res)=>{res.sendFile("public/Logged.html");});
  • 另一条路线的index.html重定向到/test如果状态是在你的Ajax响应确定。
相关问题