Javascript API数据未显示在EJS文件中

Javascript API数据未显示在EJS文件中,javascript,json,node.js,api,ejs,Javascript,Json,Node.js,Api,Ejs,我试图使用AJAX从API获取JSON数据,以显示在节点JS中的EJS文件中。然而,似乎从一开始就没有从API中提取任何内容。如何在Node JS中显示从API到页面的数据?我花了几个小时试图找到解决这个问题的办法。这是我到目前为止得到的 **index.js** var express = require('express'); var app = express(); var url = require('url'); app.set('port', (process.env.P

我试图使用AJAX从API获取JSON数据,以显示在节点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"
}
**index.js**
var express=需要(“express”);
var-app=express();
var url=require('url');
应用程序集('端口',(process.env.port | | 5000));
app.use(express.static(uu dirname+/public));
//视图是所有模板文件的目录
app.set('views','u dirname+'/views');
app.use(express.static(uu dirname+/public));
应用程序集(“查看引擎”、“ejs”);
app.get('/',函数(请求,响应){
response.render('页面/索引')
});
app.listen(app.get('port'),function(){
console.log('节点应用程序正在端口上运行',app.get('端口');
});
var http=require(“http”);
(函数($){
$(函数(){
变量状态=$(“#状态”);
getData();
函数getData(){
//从沃尔玛API获取数据
$.ajax({
url:“http://api.walmartlabs.com/v1/trends?format=json&apiKey= 
{api_key}”,
数据类型:“jsonp”,
成功:功能(数据){
//在控制台中显示此数据
控制台日志(数据);
//变量实例化
var itemId=data['items']['itemId'];
变量名称=数据['items']['name'];
var regularPrice=数据['items']['msrp'];
var salePrice=数据['items']['salePrice'];
//将数据放在HTML中
$(“#productId”).html(itemId);
$(“#名称”).html(名称);
$(“#regularPrice”).html(regularPrice);
$(“#salePrice”).html(salePrice);
}
});
}
**index.ejs**
商店应用程序
商店应用程序
欢迎访问商店节点站点。在这里,您将在
沃尔玛网站。您也可以按类别浏览或按产品id或搜索
名字

**package.json** { “名称”:“节点沃尔玛”, “版本”:“1.0.0”, “说明”:“沃尔玛网络服务”, “main”:“index.js”, “依赖项”:{ “快车”:“^4.16.3”, “ejs”:“*” }, “依赖性”:{}, “脚本”:{ “测试”:“echo\”错误:未指定测试\“&退出1” }, “存储库”:{ “类型”:“git”, “url”:“git”+https://github.com/sample/node-sample.git" }, “作者”:“样本”, “许可证”:“麻省理工学院”, “臭虫”:{ “url”:”https://github.com/sample/node-sample/issues" }, “主页”:https://github.com/sample/node-sample#readme" }
它不是那样工作的。您需要在API中进行调用以在页面上呈现它。iLife在这里不像您使用的那样工作。

像这样使用EJB

然后你可以这样做:

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
   });
});
见文件

如果要使用新语法,请执行以下操作:

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