2017-04-12 62 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響應確定。
相關問題