Я новичок в MEAN Stack и действительно столкнулся с этой проблемой.У меня есть сервер Express, который вызывает внешний API и получает данные в формате JSON.У меня также есть MEAN Stack SPA.Что я хочу сделать, так это то, что если я перейду на определенную HTML-страницу в моем SPA, а затем нажму на кнопку, она вызовет мой сервер Express, а затем получит данные API с сервера Express в json в мой HTML-клиент.Я написал следующий код, но он совсем не работает, я не получаю никакого ответа на своей странице api_data_list.html.
Моя страница api_data_list.html:
<head>
<script src="jquery-3.3.1.min.js"></script>
<script>
$(function() {
let url = "http://localhost:3000/#!/api_data_list";
$("button").click(function(e){
e.preventDefault();
var data = {
endPoint: url
};
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
alert("Data: " + JSON.stringify(data));
//$('#my_paragraph').text(data);
}
});
});
});
</script>
</head>
<h2>List of Guests from GstAPI</h2>
<button>Click here to retrieve data from GstAPI</button>
<p id="my_paragraph"></p>
<table class="table" >
<tr>
<th>SNo.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Room ID</th>
<th>Actions</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Когда я запускаю сервер (то есть localhost), это страница index.html, которая идет первой.У меня есть ссылка, которая ведет пользователя на страницу api_data_list.html.
<h2>List of Guests</h2>
<a ui-sref="api_data_list">Click here for GstAPI Guests data</a>
<table class="table" ng-if="guests.length>0">
<tr>
<th>SNo.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Room ID</th>
<th>Telephone No.</th>
<th>Actions</th>
</tr>
<tr ng-repeat="guest in guests">
<td>{{$index + 1}}</td>
<td>{{guest.firstname}}</td>
<td>{{guest.lastname}}</td>
<td>{{guest.roomid}}</td>
<td>{{guest.telephoneno}}</td>
<td>
<a ui-sref="edit({id:guest._id})">Edit</a> |
<a href="#" ng-click="deleteGuest(guest._id)">Delete</a>
</td>
</tr>
</table>
<div ng-if="guests.length==0">
No guest found !!
</div>
Мой код server.js содержит сервер Node и Express:
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
routes = require('./server/routes/web'), //web routes
apiRoutes = require('./server/routes/api'), //api routes
connection = require("./server/config/db"); //mongodb connection
var app = express();
getDataFromGstAPI();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.static('node_modules'));
app.use('/', routes);
app.use('/api', apiRoutes);
function getDataFromGstAPI(){
var client_key = [key]; //Client key
var client_secret = [secret]; // Client secret
var base64EncodedString = Buffer.from(pcc_client_key + ":" + pcc_client_secret).toString('base64'); // Key and Secret are Base64 encoded for Basic authorization
var request = require("request"); //"request" module is used for making http requests
var token = ''; //to obtain the access token
var guests = {};
getToken(); //connecting to the GstAPI server to get the token
function getToken(){
//making a POST request to server to obtain the access token for oAuth 2.0 (2-legged approach)
var options = {
method: 'POST',
url: 'https://connect.gstapi.com/auth/token',
headers: {
'authorization': 'Basic ' + base64EncodedString,
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'client_credentials'
}
};
app.post('/api_data_list', (req,res) => {
request(options, function(e,r,body) {
if(e) throw new Error(e);
token = JSON.parse(body).access_token;
getGuests(token,res);
});
});
};
function getGuests(token,res){
//making a GET request to get the API using the access token
var optionsForGETGuests = {
method: 'GET',
url: 'https://connect.gstapi.com/api/public/guests',
headers:
{
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}
};
request(optionsForGETGuests, function (e, r, body) {
if (e) throw new Error(e);
//console.log(body);
guests = JSON.parse(body);
res.send(guests);
});
};
}
var port = process.env.port || 3000;
app.listen(port, function() {
console.log("Server is running at : http://localhost:" + port);
});
Что я делаю не так?Это из-за неправильной конфигурации конечной точки или маршрутов?Или это проблема с моим кодом JQuery?