0

i want to create an article by rest services of drupal ? as given in the documentation on Drupal Post docs link

but it gives an error Reference error : Drupal is not defined

in the following line of code jQuery.get(Drupal.url('rest/session/token'))

here is my code based on docs

function getCsrfToken(callback) {
  jQuery.get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}


function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://localhost/dr/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken

    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  _links: {
    type: {
      href: 'http://localhost/dr/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'Example node title'
  }
}; 

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});

1 Answer 1

0

You need to enclose your javascript

(function ($, Drupal) {

  ...

})(jQuery, Drupal);

to access Drupal and the usual $ for jQuery.

6
  • i didn't get this why to do this ? am i doing something wrong
    – Mohd Maaz
    Oct 5, 2018 at 6:30
  • and i am still getting Reference error : Drupal is not defined in the line ` })(jQuery, Drupal) `
    – Mohd Maaz
    Oct 5, 2018 at 6:39
  • Did you declare a dependency for core/drupal in *.libraries.yml?
    – 4uk4
    Oct 5, 2018 at 6:44
  • No , i just expose my api via rest ui module as shown in the Docs and try to post and article
    – Mohd Maaz
    Oct 5, 2018 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.