简单的node服务器ajax请求

知识点

  1. 创建一个请求

    var xhr = new XMLHttpRequest();
    
  2. 准备发送

    xhr.open('get','http://localhost:3000/api/one',true);
    
  3. 执行发送动作

    xhr.send(null);
    
  4. 监听服务器响应

    xhr.addEventListener('readystatechange',function (ev2) {
        // console.log(xhr.readyState);
      if (xhr.readyState === 4){
        // 意味着服务器响应结束
        // 不代表服务器响应一定正确
        // console.log(xhr.status);
        if (xhr.status === 200){
          console.log(xhr.response);
        }
      }
    })
    
  5. xhr.readyState === 4意味着响应结束,但不一定响应正确。

  6. xhr.status 状态码

  7. xhr.response 响应结果

过程

  1. 配置好服务器后,启动服务器

  2. 在index.js中,写好接口路由和页面路由

    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    /*  页面路由 */
    router.get('/', function(req, res, next) {
      res.render('index', { title: '测试中心' });
    });
    
    /*  接口路由 */
    router.get('/api/one', function(req, res, next) {
      res.json({
        "start":200,
        "data":{
          "name":"郇凯",
          "intro":"I like zheng"
        }
      })
    });
    
    
    module.exports = router;
    
    
  3. 在index.ejs中写请求访问

    <!DOCTYPE html>
    <html lang="ch">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="id=edge">
        <title></title>
      </head>
      <body>
        <button id="send">发起get请求</button>
        <script>
          window.addEventListener('load',function (ev) {
            var btn = document.getElementById('send');
            btn.addEventListener('click',function (ev1) {
              // 1. 创建一个请求对象
              var xhr = new XMLHttpRequest();
              // 2. 准备发送
              xhr.open('get','http://localhost:3000/api/one',true);
              // 3. 执行发送动作
              xhr.send(null);
              // 4. 监听服务器响应
              xhr.addEventListener('readystatechange',function (ev2) {
                  // console.log(xhr.readyState);
                if (xhr.readyState === 4){
                  // 意味着服务器响应结束
                  // 不代表服务器响应一定正确
                  // console.log(xhr.status);
                  if (xhr.status === 200){
                    console.log(xhr.response);
                  }
                }
              })
            });
          })
        </script>
      </body>
    </html>
    
    
发布了270 篇原创文章 · 获赞 123 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/KaiSarH/article/details/104527892