2017-06-13 217 views
1

使用express可以从Wordpress API制作外部http获取请求吗?使用Express和NODEJS的Wordpress API

假设我想向http://demo.wp-api.org/wp-json/wp/v2/posts发送获取请求 - 这是来自wordpress的帖子列表。

样品:

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 
} 
+0

当然。使用'request'模块:https://www.npmjs.com/package/request –

+0

谢谢。它已经在工作了。我会进行更新。 –

回答

1

更新(我看着办吧):

我用的请求模块,所以任何人都与它有麻烦谁。您可以在您的控制器内调用此功能:

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); 
    }