如何使用Ajax将JSON从服务器端(nodejs)发送到客户端?

时间:2019-11-01 18:26:10

标签: javascript node.js ajax rest express

我已经创建了一个Node.js / express服务器来获取调用API。该API返回json数据。如何将收到的JSON发送到本地javascript(客户端-服务器)?我想获取此JSON,发送到我的本地客户端(如果可以的话,使用ajax调用),循环遍历并将其附加到我的DOM!

app.js

var express = require('express');
var router = express.Router();
var request = require("request");

let name, value, bodyData;

var options = { method: 'GET',
  url: 'https://api.example.com/data1',
  qs: 
   { 
     valueType: 'MAXIMUM'
   },
  headers: 
   { 
     authorization: 'ABC123456',
     accept: 'application/json; charset=utf-8' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  bodyData = body;

});


router.get('/', function(req, res, next) {
  res.render('home', {data: bodyData});
});

module.exports = router;

app.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Items</title>
</head>
<body>
  <div id="itemsList">
    <h2>List of available items:  </h2>
  </div>
</body>
</html>

scripts.js

$(document).ready(function(){
   $.ajax({
       type: "GET",
       url: "http://localhost:3000/",
       contentType: "application/json"
     }).done(function(data){
          for(var i =1; i<= 10; i++){
          $('#itemsList').append('<div id="r'+ i +'"></div>')
          }
     })
 });

2 个答案:

答案 0 :(得分:0)

var express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));


app.get('/', (request, response)=>{
  response.json({
    message: 'Hello world!',
    arrayText: ['message1', 'message2']
  }):
});

答案 1 :(得分:0)

如果您的data是一个数组,则应该以这种方式编写循环:

$(document).ready(function(){
   $.ajax({
       type: "GET",
       url: "http://localhost:3000/",
       contentType: "application/json"
     }).done(function(data){
          for(var i =1; i<data.length; i++){
          $('#itemsList').append('<div id="r'+ data[i] +'">'+data[i]+'</div>')
          }
     })
 });