Advertisement
nubilfi

jQuery AJAX - CSRF 500 internal server error

Jun 19th, 2017
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // USER SIGN UP ==============================================================
  2. app.get('/user/create', isLoggedIn, (req, res, next) => {
  3.   let messages = req.flash('error');
  4.   res.json({ csrfToken: req.csrfToken() });
  5. });
  6.  
  7. // Handle user create on POST =============================================
  8.   app.post('/user/create', isLoggedIn, (req, res, next) => {
  9.     req.checkBody('username').notEmpty();
  10.     req.checkBody('password').notEmpty();
  11.  
  12.     req.sanitize('username').escape();
  13.     req.sanitize('username').trim();
  14.     req.sanitize('password').trim();
  15.  
  16.     let newUser = new User({
  17.       username: req.body.username,
  18.       password: req.body.password
  19.     });
  20.  
  21.     let errors = req.validationErrors();
  22.     if (errors) {
  23.       res.json({ csrfToken: req.csrfToken() });
  24.     } else {
  25.       // Data from form is valid, lets save it
  26.       newUser.save((err) => {
  27.         if (err) {
  28.           return next(err);
  29.         }
  30.  
  31.         res.redirect('/user');
  32.       });
  33.     }
  34.   });
  35.  
  36. #####################################################################################
  37. <button type="button" name="button" class="btn btn-primary" id="add-user">
  38.    <i class="fa fa-plus" aria-hidden="true">&nbsp;New User</i>
  39. </button>
  40.  
  41. ======= Modal - Form Create User =======
  42. <form action="/user/create" id="account-form" class="form-horizontal" method="post">
  43.     <div class="col-md-12">
  44.       <div class="form-group">
  45.           <label for="username" class="col-md-3 control-label">Username</label>
  46.           <div class="col-md-8">
  47.               <input type="text" name="username" class="form-control" id="username" placeholder="Username"/>
  48.           </div>
  49.       </div>
  50.       <div class="form-group">
  51.           <label for="password" class="col-md-3 control-label">Password</label>
  52.           <div class="col-md-8">
  53.               <input type="password" name="password" class="form-control" id="password" placeholder="Password"/>
  54.           </div>
  55.       </div>
  56.     </div>
  57.     <div class="form-group">
  58.         <div class="col-sm-6 col-sm-offset-6">
  59.             <input type="hidden" id="token-key" name="_csrf">
  60.             <button type="submit" name="button" class="btn btn-primary">
  61.                 <i class="fa fa-save"></i>
  62.                 &nbsp;Process
  63.             </button>
  64.         </div>
  65.     </div>
  66. </form>
  67.  
  68. ====== Show Modal & set the csrfToken value =========
  69. $('#add-user').click(function () {
  70.  
  71.   var url = "http://localhost:3000/user/create";
  72.  
  73.   $.ajax({
  74.     type: "GET",
  75.     url: url,
  76.     dataType: "json",
  77.     success: function (data) {
  78.       var token = data.csrfToken;
  79.  
  80.       $('input[name="_csrf"]').val(token);
  81.       $('#modal-adduser').modal('show');
  82.     }
  83.   });
  84. });
  85.  
  86. ========== Event for form submit ==============
  87. $('form#account-form').submit(function (event) {
  88.   event.preventDefault();
  89.  
  90.   var urlcreate = "http://localhost:3000/user/create";
  91.   var formData = {
  92.     'username': $('input[name="username"]').val(),
  93.     'password': $('input[name="password"]').val()
  94.   };
  95.  
  96.   $.ajaxSetup({
  97.       headers:
  98.       { 'X-CSRF-TOKEN': $('input[name="_csrf"]').val() }
  99.   });
  100.  
  101.   $.ajax({
  102.     type: "POST",
  103.     url: urlcreate,
  104.     data: formData,
  105.     dataType: "json",
  106.     success: function (result) {
  107.       console.log(result);
  108.     }
  109.   });
  110.  
  111. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement