Wordpress API with Express and NODEJS

Is it possible to make an external http get request from Wordpress API using express?

Let's say I want to make a get request to http://demo.wp-api.org/wp-json/wp/v2/posts - This are a list of posts from wordpress.

Sample:

router.get('/posts', function(req, res){
     I should make an external http get request here from wordpress api
     ("http://demo.wp-api.org/wp-json/wp/v2/posts")

     Then I want to display the response as json
}

Upvotes: 2

Views: 3412

Answers (1)

Update (I figure it out):

I use the request module, so to anyone whose having trouble with it. You can call this function inside your controller:

var express = require("express");
var request = require("request");
var router = express;

var getWPPost = function(req, res){
    var headers, options;

    // Set the headers
    headers = {
        'Content-Type':'application/x-www-form-urlencoded'
    }

    // Configure the request
    options = {
        url: 'http://demo.wp-api.org/wp-json/wp/v2/posts/1',
        method: 'GET',
        headers: headers
    }

    // Start the request
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res.send({
               success: true,
               message: "Successfully fetched a list of post", 
               posts: JSON.parse(body)
            });
        } else {
             console.log(error);
        }
     });
   };

  router.get('/post', function(req, res){
       getWPPost(req, res);
  }

Upvotes: 1

Related Questions