将JSON数据从Express服务器发送到客户端

时间:2018-09-18 17:11:44

标签: jquery node.js ajax express mean-stack

我是MEAN Stack的新手,但确实受此问题困扰。我有一个Express服务器,该服务器正在调用外部API并以JSON格式获取数据。我也有一个MEAN Stack SPA。我想做的是,如果我进入SPA中的某个html页面,然后单击按钮,它将调用Express服务器,然后将json中Express服务器的API数据获取到我的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>

当我运行服务器(即本地主机)时,这是第一个出现的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代码有问题?

1 个答案:

答案 0 :(得分:0)

您可能应该更改

let url = "http://localhost:3000/#!/api_data_list";

收件人:

let url = "http://localhost:3000/api_data_list";

请注意,第二个示例没有#!