在EJS文件中不显示API数据

时间:2018-04-11 11:09:16

标签: javascript json node.js api ejs

我正在尝试使用AJAX从API中获取JSON数据,以显示在Node JS中的EJS文件中。但是,似乎首先没有从API中提取任何内容。如何在API JS中显示API中的数据?我一直在努力寻找解决方案。这是我到目前为止所做的。

**index.js**

 var express = require('express');
 var app = express();
 var url = require('url');

 app.set('port', (process.env.PORT || 5000));

 app.use(express.static(__dirname + '/public'));

 // views is directory for all template files
 app.set('views', __dirname + '/views');
 app.use(express.static(__dirname + '/public'));
 app.set('view engine', 'ejs');

 app.get('/', function(request, response) {
  response.render('pages/index')
 });

 app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
 });

 var http = require("http");

 (function($) {
    $(function() {

          var status = $('#status');
          getData();

          function getData() {
            // Get the data from the Walmart API
            $.ajax({
              url: "http://api.walmartlabs.com/v1/trends?format=json&apiKey= 
 {api_key}",
              dataType: "jsonp",
              success: function(data) {
                //Show this data in the console
                console.log(data);
                //variable instantiation
                var itemId = data['items']['itemId'];
                var name = data['items']['name'];
                var regularPrice = data['items']['msrp'];
                var salePrice = data['items']['salePrice'];

                //Place data in HTML
                $("#productId").html(itemId);
                $("#name").html(name);
                $("#regularPrice").html(regularPrice);
                $("#salePrice").html(salePrice);
              }
            });

          }

**index.ejs**
    <!DOCTYPE html>
<html>

<head>
  <title>Store App</title>
  <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
</script>
  <script type="application/json" src="/js/index.js"></script>
</head>

<body>

  <h1>Store App</h1>

  <p>Welcome to the Store Node site. Here, you will find hot products on the 
Walmart website. You can also browse by category or search by product id or 
name.</p>

  <section class="item-container">
    <h1 id="name"></h1>
    <ul id="current_trends">
      <li id="productId"></li>
      <li id="regularPrice"></li>
      <li id="salePrice"></li>
    </ul>
  </section>

  <script 
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"> 
 </script>
</body>

</html>

**package.json**

 {
  "name": "node-walmart",
  "version": "1.0.0",
  "description": "walmart web services",
  "main": "index.js",
  "dependencies": {
    "express": "^4.16.3",
    "ejs": "*"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sample/node-sample.git"
  },
  "author": "sample",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/sample/node-sample/issues"
  },
  "homepage": "https://github.com/sample/node-sample#readme"
}

2 个答案:

答案 0 :(得分:2)

像这样使用EJS Node-Cheat

然后你就可以这样做:

app.get('/', function(req, res, next) {
    //see message is passed to index.ejs and ejs will take care of rendering it
    //so same way you can load your api data here like:  
    axios.get('http://api.walmartlabs.com/v1/trends?format=json&apiKey={api_key}')
   .then(function (apiData) {
      //now pass apiData to index.ejs to take care of it
      res.render('index',{message:"Hello World!", apiData: apiData});
    })
   .catch(function (error) {
      //render your error.ejs here
   });
});

请参阅axios docs here

如果您想使用新语法:

app.get('/', async (req, res, next) => {
        //see message is passed to index.ejs and ejs will take care of rendering it
        //so same way you can load your api data here like:  
        try {
           const apiData = axios.get('http://api.walmartlabs.com/v1/trends?format=json&apiKey={api_key}');
           //now pass apiData to index.ejs to take care of it
           res.render('index',{message:"Hello World!", apiData: apiData});
        }
        catch (e){
           //render your error.ejs here
        }
    });

答案 1 :(得分:0)

它不会那样工作。您需要在API中进行调用以在页面上呈现它。 IIFE不会像你一样在这里工作。