0

I'm trying to use the RESTful service for creating a node with Javascript using the script below, but I only receive a 400 (Bad Request) error. I have enabled all the formats and set permissions for authenticated users.

The reports shows the following error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: No route found for "GET /entity/node": Method Not Allowed (Allow: POST) in Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest() (line 163 of /Applications/MAMP/htdocs/comedinewithme/vendor/symfony/http-kernel/EventListener/RouterListener.php).

Do I need to set an authorization in the header? Isn't this what the csrf token is for though? And how should this be formatted? I'm completely lost!

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://example.com/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://example.com/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'Example node title'
  }
}; 

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

Figured it out: for the _links href I was using a relative URL instead of absolute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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