Monday, 22 May 2017

AJAX won't make "patch" request in Node + Express

I'm building a weather app that allows a user to login and get the weather of a particular city by entering the location in an input which makes a GET request to the OpenWeatherMap API. I have built in a feature that allows the user to set the location that they have looked up as their homepage weather. My reasoning was to assign an attribute in the User model called "location", and update it whenever the user clicks the "set as homepage weather". I am attempting to use AJAX to make the patch request, but even when the success function is fired on the request, the model is not updated.

Here is my AJAX request:

var userId = $('.set-weather').attr('data-id')
$(document).on('click', '.location-btn', function(){
    console.log(setLocation)
    var data = {
        location: setLocation
    }
    console.log("/users/" + userId)
    $.ajax({
      url: '/users/' + userId,
      method: 'patch',
      dataType: "json",
      data: ({location: data}),
      success: function(result){
        console.log("Success")
      },
      error: function(result){
        console.log("failure")
      }
    })
  })

Here is the User model using Node and Express:

// app/models/user.js
// load the things we need
var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

// define the schema for our user model
var userSchema = mongoose.Schema({


    email        : String,
    password     : String,
    location     : String,


});

// methods 
// generating a hash
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};

// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);

Routes to the User API:

router.route('/users/:id')
  .get(userController.show)
  .patch(userController.update)

And Update method in the controller:

controller.update = function(req, res){
  var id = req.params.id;
  var location = req.params.location;
  User.findOneAndUpdate(
    {_id: id},
    {
      location: location
    },
    function(err, user){
      if(err){
        throw err;
      }
      res.json(user)
    }
    )
}



via Ian Springer

No comments:

Post a Comment