2017-09-27 77 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 
} 

我不知道这是否会工作,我没有测试过,但我觉得你得到的理念。