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'
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.

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.