javascript - API 数据未显示在 EJS 文件中

标签 javascript json node.js api ejs

我正在尝试使用 AJAX 从 API 获取 JSON 数据,以显示在 Node JS 中的 EJS 文件上。然而,似乎一开始就没有从 API 中提取任何内容。如何在 Node 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"
}

最佳答案

像这样使用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文档 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
        }
    });

关于javascript - API 数据未显示在 EJS 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49773543/

相关文章:

node.js - 在 Express 中包含 Bootstrap Glyphicons

javascript - 为什么我的退出进程在循环结束之前执行?

javascript - 使用jquery通过选择器获取html表单值

javascript - 如何在 React.js 中获取 JSON 对象的键和值

php - 如何优化 jquery 选择的插件以加载超过 50k 结果

java - 字符串org.json.JSONException : Unterminated object at character

javascript - 当我更改 http.jsonp() URL 时,JSON 数据未显示

javascript - Node.js 与 CoffeeScript,如何调试?

javascript - Onclick 事件无法在 IE 11 中的 <option> 标记上工作

javascript - 如何从 Javascript 中的数组中提取值?