J'essaie d'utiliser AJAX pour obtenir les données JSON d'une API afin de les afficher sur mon fichier EJS dans Node JS. Cependant, il semble que rien ne soit tiré de l'API en premier lieu. Comment puis-je afficher les données d'une API sur une page en Node JS ? J'ai essayé pendant des heures de trouver une solution à cette question. Voici ce que j'ai obtenu jusqu'à présent.
**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"
}