简体   繁体   English

Expressjs使用来自REST Api的请求主体

[英]Expressjs use request body from REST Api

I am experimenting with nodejs / expressjs for our webclient and am having trouble passing the data to my .ejs template: 我正在为我们的Web客户端尝试使用nodejs / expressjs,但无法将数据传递到我的.ejs模板中:

I have an REST API call to our application server which returns a json element. 我有一个对我们的应用程序服务器的REST API调用,它返回一个json元素。 I was hoping I could call the API directly in the router and pass it as a variable to my template but I can't seem get extract the json element. 我希望我可以直接在路由器中调用API并将其作为变量传递给我的模板,但是我似乎无法提取json元素。 I know I could use an ajax call directly in the template, but I wanted to try to stick to an MVC Design pattern. 我知道我可以直接在模板中使用ajax调用,但是我想尝试坚持使用MVC设计模式。

returning the json element to a local variable which I then pass doesn't seem to work for some reason. 返回json元素到我随后通过的局部变量,由于某种原因似乎不起作用。

I've been scouring the internet the entire day trying to find an answer, but in all the tutorials all I've seen is everyone just logging their result. 我整天都在搜寻互联网以寻找答案,但是在所有教程中,我所看到的只是每个人都在记录他们的结果。 That's all well and good but it would be nice to do something with it. 一切都很好,但是用它做点事会很好。

` `

    var url = "http://application.server"

    /* GET home page. */
    router.get('/', function(req, res, next) {

  request(url, function (error, response, body) {
    console.log(body); //returns Json element, how can I extract this??
  });

  res.render('index', {
    //data: body <---- I want to pass the JSON element to my template here
  });

    });

` `

thank you!!!! 谢谢!!!!

@Phil Thanks for the completely logical answer :) @Phil感谢您提供完全合乎逻辑的答案:)

I now render my template within the callback and parse body to a JSON object with JSON.parse(body) . 我现在在回调中呈现我的模板,并解析body的JSON对象与JSON.parse(body) Later I will have to make more API calls and pass them but for our prototype this works. 稍后,我将不得不进行更多的API调用并传递它们,但对于我们的原型,它可以工作。

var url = "http://application.server"

/* GET home page. */
router.get('/', function(req, res, next) {
  request(url, function (error, response, body) {
    res.render('index', {data:JSON.parse(body)});
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM