Search code examples
javascriptmeteormeteor-blaze

MeteorJS call rest api server side


Now i call rest API with:

Template.accedi.events({
  'submit #form-login'(e) {
    e.preventDefault();
    var data = {
      'username': $("[name=login_username]").val(),
      'password': $("[name=login_password]").val()
    };
    var url = api_url + "/Token";

    HTTP.call('POST', url, {
      params: { 
        'grant_type': 'password', 
        'username': data.username,
        'password': data.password
      }
    }, (error, result) => {
      if (!error) {
        Session.set('userData', JSON.stringify(result.data));
        localStorage.setItem('userData', JSON.stringify(result.data))
        Router.go('/');
      }
    }
  }
})

This call rest api client side. I need to call the api server side... there is a method?


Solution

  • You should create method which is then called from your client code. Something like below should works in your case.

    Methods have to be defined in code which is loaded on the client and server.

    Meteor.methods({
      'login.token'({ username, password }) {
        try {
          let request = HTTP.call('POST', 'https://example.com', {
            params: { 
              'grant_type': 'password', 
              'username': username,
              'password': password
            }
          })
    
          // You might want to process, validate etc. request response before return it to the client.
          return request 
        } catch (err) {
          throw new Meteor.Error(500, 'There was an error processing your request')
        }
      }
    })
    

    Your client code might looks similiar to this

    Template.accedi.events({
      'submit #form-login'(e) {
        e.preventDefault();
        var data = {
          'username': $("[name=login_username]").val(),
          'password': $("[name=login_password]").val()
        };
    
        Meteor.call('login.token', {
          username: data.username,
          password: data.password
        }, (err, res) => {
          if (err) {
            console.log(err)
          } else {
            Session.set('userData', JSON.stringify(res.data));
            localStorage.setItem('userData', JSON.stringify(res.data))
            Router.go('/');
          }
        })
      }
    })
    

    You can find more about methods in Meteor guide at this page https://guide.meteor.com/methods.html