【问题标题】:Sending JSON data from Express server to client从 Express 服务器向客户端发送 JSON 数据
【发布时间】:2018-09-18 17:11:44
【问题描述】:

我是 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>

当我运行服务器(即 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 代码有问题?

【问题讨论】:

  • 您必须做一些功课并缩小此处的问题范围。使用您的控制台端到端跟踪请求 - 您是否遇到错误?来自浏览器的请求是否得到响应?服务器是否与 API 通信?进行基本调试,然后返回更具体的问题
  • 我没有看到该页面的配置路由,您只是在服务器的全局范围内调用getDataFromGstAPI()
  • @WillardSolutions 嗨,抱歉,我的问题无法正确解释。我做了一些调试,也使用了 Postman,我发现服务器与 API 通信,服务器从 API 获取数据。我在这里面临的唯一问题是来自浏览器(即客户端 jqeury)的请求没有得到任何响应。

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


【解决方案1】:

你应该改变

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

到:

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

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

【讨论】:

  • 嗨雅各布!非常感谢您的回答。我也将网址更改为您喜欢的形式。但是,我仍然没有收到 Express 服务器的任何响应。
  • 我刚刚检查了 Postman,但是没有,我没有收到来自 Postman 中 localhost:3000/pcc_list 的任何响应。
  • 我认为那是因为您永远不会调用 getDataFromGstAPI() 或 getToken() ,因此永远不会注册端点。这意味着 express 不知道端点存在。
猜你喜欢
  • 2014-09-07
  • 1970-01-01
  • 2015-02-10
  • 2019-01-01
  • 1970-01-01
  • 2020-04-16
  • 2015-02-17
  • 1970-01-01
  • 2015-07-09
相关资源
最近更新 更多