1. <!DOCTYPE html>
    2. <html lang="zh">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>TestAjax</title>
    6. <style>
    7. #result{
    8. width: 200px;
    9. height: 100px;
    10. border: solid 1px #2a5caa;
    11. }
    12. </style>
    13. </head>
    14. <body>
    15. <button>发送请求</button>
    16. <div id="result"></div>
    17. <script>
    18. const btn = document.getElementsByTagName('button')[0];
    19. const result = document.getElementById('result');
    20. window.onkeydown = function (){
    21. const xhr = new XMLHttpRequest();
    22. xhr.responseType = 'json';// 对json数据进行转化-----自动
    23. xhr.open('GET','http://localhost:8000/HandleJson');
    24. xhr.send();
    25. xhr.onreadystatechange = function (){
    26. if (xhr.readyState === 4){
    27. if (xhr.status >= 200 && xhr.status < 300){
    28. // 对json数据进行转化-----手动
    29. // let data = JSON.parse(xhr.response);
    30. // console.log(data);
    31. // result.innerHTML = data.name;
    32. // 对json数据进行转化-----自动
    33. result.innerHTML = xhr.response.name;
    34. }
    35. }
    36. }
    37. };
    38. </script>
    39. </body>
    40. </html>
    1. // 1.引入express
    2. const express = require('express')
    3. // 2.创建应用对象
    4. const app = express()
    5. // 3.创建路由规则
    6. app.all('/HandleJson', (request,response) =>{
    7. // 设置响应头
    8. response.setHeader('Access-Control-Allow-Origin','*') // 设置允许跨域
    9. response.setHeader('Access-Control-Allow-Headers','*') // 设置所有请求头都可以允许书写
    10. // 设置响应体
    11. const data = {
    12. name : 'test'
    13. }
    14. // 对象与字符串转化
    15. let str = JSON.stringify(data);
    16. response.send(str);
    17. });
    18. // 4.监听端口,启动服务
    19. app.listen(8000,()=>{
    20. console.log("服务已启动");
    21. });