美文网首页
用node写一个属于自己的API接口。

用node写一个属于自己的API接口。

作者: 似朝朝我心 | 来源:发表于2020-10-21 19:28 被阅读0次

需要掌握基础的node知识和Ajax请求知识。

1.目录结构如下。

2.完整代码展示及注释:

data.json (模仿后台数据)

{
  "data": { 
    "returnCode": "SUCCESS", 
    "success": true,
    "banner": "双十一大抢购!go!go!go!",
    "list": [
      {
        "title": "入秋穿搭指南",
        "imgage": "xxx.jpg"
      },
      {
        "title": "秋季护肤大作战",
        "imgage": "xxx.jpg"
      },
      {
        "title": "流行套装抢先一步",
        "imgage": "xxx.jpg"
      },
      {
        "title": "焕新时尚周",
        "imgage": "xxx.jpg"
      },
      {
        "title": "好物特卖",
        "imgage": "xxx.jpg"
      }
    ]
  }
}

server.js (搭建服务器)

const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {//创建一个服务器实例,传入一个回调函数
  const url = request.url;
  if (url === '/') {//如果请求到的路径是当前路径,则执行这里面的内容
    fs.readFile('./index.html', (err, data) => {//读取我们当前的index.html页面状态
      if (!err) {//如果没有报错的话,就执行这里的代码
        //设置响应头和200状态码(成功)
        response.writeHead(200, {"Content-Type":"text/html;charset=utf-8"})
        //1.statusCode:HTTP状态码,如200(请求成功)
        //2.设置服务器端返回数据的方式和类型,防止中文乱码
        response.end(data);//此方法向服务器发出信号,表明已发送所有响应头和主体
      }else {
          throw err;//抛出错误
      }
    });
  }else if (url === '/data') {
      fs.readFile('./data.json', (err, data) => {
        if (!err) {
            response.writeHead(200, {"Content-Type":"application/json"})
            response.end(data)
        }else {
            throw err;
        }
      })
  }else {
      
  }
});
server.listen(8080);//监听端口
console.log(`server is running at http://127.0.0.1:8080`)

index.html (发送ajax,请求数据)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<!-- 发送ajax请求 -->
<button onclick="success()">发送请求</button>
<script>
  function success() {
    const http = new XMLHttpRequest();//创建一个XHR的实例对象
    http.onreadystatechange = () => {//绑定一个 readystatechange 事件,用于监听http.status和http.readyState的属性变化
      if (http.status == 200 && http.readyState == 4) {//判断状态:200是成功的状态码、readyState是响应阶段,有0-4共5个响应阶段,4代表的是已接收到全部的响应
        const result = JSON.parse(http.responseText);//接收服务器端返回的文本信息并且通过JSON.parse()方法解析文本信息
        //为什么需要解析服务器端返回的文本信息,因为服务器端返回的文本信息是二进制的Buffer流
        console.log(result)
      }
    }
    http.open('GET', '/data');//创建一个get请求,携带参数数据
    http.send()//发送请求
  }
</script>
</body>
</html>

3.运行服务器。

4.效果展示。

附:对于ajax请求不是很了解的,可以看下这个:https://blog.csdn.net/l_ppp/article/details/108921610?utm_medium=distribute.pc_category.none-task-blog-hot-5.nonecase&depth_1-utm_source=distribute.pc_category.none-task-blog-hot-5.nonecase&request_id=
对于服务器搭建不是很了解的,可以看下这个:https://www.liaoxuefeng.com/wiki/1022910821149312/1023025830950720

相关文章

网友评论

      本文标题:用node写一个属于自己的API接口。

      本文链接:https://www.haomeiwen.com/subject/xheemktx.html