(过程)服务端响应客户端数据,并由客户端接收服务端发送的数据(及两种方式)
3-JSON.html('手动转换'由服务端发来的数据)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Json响应title>
<style>
#result{
width:200px;
height:100px;
border:solid 1px #4fad09;
}
style>
head>
<body>
<div id="result">div>
<script>
//获取元素对象
const result=document.getElementById('result');
//绑定键盘按下事件
window.onkeydown=function(){
//发送请求
const xhr=new XMLHttpRequest();
//初始化
xhr.open('GET','http://127.0.0.1:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status<300){
// console.log(xhr.response);
// result.innerHTML=xhr.response;
//手动对数据转化
let data=JSON.parse(xhr.response);
console.log(data);
result.innerHTML=data.name;
}
}
}
}
script>
body>
html>
3-JSON.html('自动转换'由服务端发来的数据)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Json响应title>
<style>
#result{
width:200px;
height:100px;
border:solid 1px #4fad09;
}
style>
head>
<body>
<div id="result">div>
<script>
//获取元素对象
const result=document.getElementById('result');
//绑定键盘按下事件
window.onkeydown=function(){
//发送请求
const xhr=new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType='json';
//初始化
xhr.open('GET','http://127.0.0.1:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status<300){
// console.log(xhr.response);
// result.innerHTML=xhr.response;
//自动对数据转化
console.log(xhr.response);
result.innerHTML=xhr.response.name;
}
}
}
}
script>
body>
html>
服务端server.js
//1.引入express const express=require('express'); //2.创建应用对象 const app=express(); //3.创建路由规则 //request是对请求报文的封装 //response是对响应报文的封装 app.all('/json-server',(request,response)=>{ //设置响应头 允许跨域 response.setHeader('Access-Control-Allow-Origin','*'); //响应头 response.setHeader('Access-Control-Allow-Headers','*'); //响应一个数据 const data={ name:'atguigu' }; //对对象进行字符串转换 let str=JSON.stringify(data); //设置响应体 response.send(str); }); //4.监听端口启动服务 app.listen(8000,()=>{ console.log("服务已经启动,8000端口监听中......"); })
页面效果:(键盘按下任意键,控制端都会返回如下结果,绿框中显示从服务端接收的数据)