I will be writing a series of article on Drupal-8 Headless. This article will focus on simple headless hello world. We will first learn how to create a Hello World Module in Drupal-8. Oh! but this hello world page will return JSON Data :-) Then we will be creating a NodeJS+Express project which consume the JSON data from Drupal and display it.
Node JS
It’s like Apache server for PHP. Just like Drupal Application needs Apache or Nginx. For running a Javascript Application on Server we require Node JS to be installed. Read more about installing and using Node JS.
Express JS
Express JS is a server side Javascript framework that provides features including server side routing, MVC, etc.
- Install a standard drupal-8 profile
- Create hello world module
Create a helloworld folder in modules directory.
Create a file name helloworld.info.yml with content
Create a file name helloworld.routing.yml with content
name: helloworld type: module description: Hello World JSON Return core: 8.x package: Other
Create new directories src and src/Controller. Create file src/Controller/DefaultController.php with below codeheaders->set('Content-Type', 'application/json'); return $response; } }
- Enable the Hello World Module in Drupal
- Create a new Node Project (say meand8)
From your terminal type:$ mkdir meand8 $ cd meand8 $ npm init # initiate the node project. Choose all default options. $ npm install express —save # add dependency on express js.
It will create a file named package.json with content similar to:{ "name": "meand8", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\"&& exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.13.3", } }
Create new file index.js with following content
var express = require('express'); var http = require('http'); var app = express(); var http = require('http'); /* Assuming that you can access your drupal via http://localhost/d8 Make a http get request to drupal hello world page, that returns a JSON */ http.get("http://localhost/d8/helloworld", function(res) { console.log("Got response: " + res.statusCode); res.on("data", function(chunk) { http_req = "" + chunk; }); }).on('error', function(e) { console.log("Got error: " + e.message); }); /*Create the landing page of Express JS App and return the Content from Drupal Hello World Page app.get('/', function(req, res) { res.send(http_req); }); app.listen(3000); console.log('Listening on port 3000...');
- Start your node server
In terminal type $ node index.js Listening on port 3000... Got response: 200
- Check in browser localhost:3000