2017-09-27 78 views
3

我正在開發Swift 4和Vapor 2.0的Web應用程序。我有一個POST請求,這將創建一個新用戶的方法:在Vapor中爲html添加腳本動作

builder.post("user", "createUser") { (request) -> ResponseRepresentable in 

但我不知道如何在.leaf文件中添加了動作按鈕調出createUser方法。很容易在.html文件中添加JavaScript操作,如<script src="js/index.js"></script>。但隨着蒸氣,我沒有看到Vapor 2.0 docs

更新有關的任何提及:

與@Caleb Kleveter的幫助下,現在它的工作。我更新了html頁面(只是爲了測試,所以這不是一個好的頁面):它會幫助新手面臨同樣的問題,使用vapor

這裏是我的HTML內容:

<!DOCTYPE html> 
<html > 
    <head> 
     <meta charset="UTF-8"> 
      <title>Responsive Login Form</title> 


      <link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'> 

       <link rel="stylesheet" href="styles/app.css"> 


       </head> 

       <body> 
       <link href='https://fonts.googleapis.com/css?family=Ubuntu:500' rel='stylesheet' type='text/css'> 
       <h3> 
       <form action="/user/createUser" method="POST" class="login-form"> 
       <label for="username">Username:</label> 
       <input type="text" placeholder="Username" name="username"/> 
       <label for="password">Password:</label> 
       <input type="password" placeholder="Password" name="password"/> 
       <input type="submit" value="Login" class="login-button"/> 
       <form> 
       </h3> 
       <a class="sign-up">Sign Up!</a> 
       <br> 
       <h6 class="no-access">Can't access your account?</h6> 
       </div> 
       </div> 
       <!-- <div class="error-page"> 
        <div class="try-again">Error: Try again?</div> 
       </div> --> 
       <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> 
        <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> 

        <script src="js/index.js"></script> 

      </body> 
</html> 

回答

3

腳本可以被添加到一個.leaf文件的方式,你會在HTML,只需添加一個腳本標籤:

<script src="js/index.js"></script> 

查看您的代碼,你想要的是一個form將數據發佈到服務器。此時應更換你的.login-formdivform元素:

<form action="/create-user" method="POST" class="login-form"> 
    <label for="username">Username:</label> 
    <input type="text" placeholder="Username" name="username"/> 
    <label for="password">Password:</label> 
    <input type="password" placeholder="Password" name="password"/> 
    <input type="submit" value="Login" class="login-button"/> 
<form> 
<a class="sign-up">Sign Up!</a> 
<h6 class="no-access">Can't access your account?</h6> 

Here is the documentation HTML表單。

那麼你應該能夠request.body訪問你的路由方法表單數據:

func createUser(req: Request) throws -> ResponseRepresentable { 
    guard let password = req.body["password"]?.string, 
      let username = req.body["username"]?.string else { 
      throw Abort.badRequest 
    } 

    // The rest of your code goes here 
} 

我不知道這是否會工作,我沒有測試過,但我覺得你得到的理念。