0

From VueJS, I am sending a POST HTTP request to my Drupal 8 controller.

Here is my Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class ExampleController extends ControllerBase {

  public function doSomething( Request $request) {

    \Drupal::logger('mymodule')->notice($request->getContent());
    \Drupal::logger('mymodule')->notice($request->request->get('message'));

    return [];
  }
}

The first log entry outputs:

@"params":{"message":"hello world","headers":@"Content-Type":"application/json; charset=UTF-8","Access-Control-Allow-Origin":"http://localhost:8080"}

The second log entry fails (it is empty).

What am I doing wrong and how am I supposed to retrieve this message POST parameter?

For completeness, here is the JS POST request:

this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}).then(response => {
  // response
}, response => {
  // error callback
});

mymodule.routing.yml file:

mymodule.api_example:
  path: 'simple_path'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ExampleController::doSomething'
  methods: [POST]
  requirements:
    _access: 'TRUE'
2
  • Could you link to the documentation of the JS API you are using? Apr 10, 2019 at 10:48
  • github.com/pagekit/vue-resource - that said I think I just found what the issue is... will post an answer in a bit if this is confirmed ;)
    – MrUpsidown
    Apr 10, 2019 at 10:59

1 Answer 1

0

Apparently with Vue Resource, I need to add emulateJSON:

emulateJSON boolean Send request body as application/x-www-form-urlencoded content type.

this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}, {
  emulateJSON: true
}).then(response => {

  console.log(response);

}, response => {
  // error callback
});

Now in my D8 backend:

$params = $request->request->get('params');
$message = $params['message'];

And now it works as expected.

1
  • FWIW, if you create a REST endpoint by extending RestResource then you can control and handle the request format more easily, eg for JSON POST. Dec 25, 2021 at 11:37

Your Answer

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

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