使用express的http模块调用api时出错

iszxjhcz  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(175)

我想显示“太空人列表”,并通过向他们的url发出http get请求,使用太空人api实现它-http://api.open-notify.org/astros.json
我用文件实现了这个项目-
server.js-我的服务器在服务器端运行代码
index.html-用户的第一页
index.js-操纵index.html添加按钮以检查空间中的人员
预期输出-希望列出ul,以显示我们从他们的api获得json响应的所有人。
使用express的server.js文件-

const express = require("express");
const http = require("http");

const app = express();

const URL = "http://api.open-notify.org/astros.json";

http.get(URL, function(response){
   response.on("data", function(data){
      const peopleData = JSON.parse(data);
      const people = peopleData.people;
      const server = http.createServer(function(req, res){
         res.statusCode = 200;
         res.setHeader('Content-Type', 'application/json');
         res.setHeader('Access-Control-Allow-Origin','*');
         res.write(JSON.stringify(people));
      });
   });
});

app.listen(3000, function(){
   console.log("Server started on Port : 3000");
});

index.html和index.js-

window.addEventListener('DOMContentLoaded', function(event){
   console.log("DOM Fully Loaded and Parsed");

   let body = document.querySelector('body');

   let h3 = document.createElement('h3');
   h3.innerText = "People in Space Right Now!";
   body.appendChild(h3);

   let button = document.createElement('button');
   button.innerText = "Who is in Space ?";
   body.appendChild(button);

   button.addEventListener('click', getPeople);

   function getPeople(){
      fetch('http://localhost:3000')
      .then(response => response.json())
      .then(people => {
         let ul = document.createElement('ul');
         body.append(ul);
         people.map(function(p){
            let li = document.createElement('li');
            li.innerHTML = `<h4>${p.name}</h4>
            <p>Assigned To : ${p.craft}</p>`
            ul.append(li);
         });      
      });
   }
});
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>People In Space</title>
</head>
<body>
   <script src="index.js" charset="utf-8"></script>
</body>
</html>

错误-单击按钮时出错

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题