服务端
express框架
由于response.end();只支持两种数据类,一种是二进制,一种是字符串,需要首先对数据进行转换成为字符串
//响应一个数据
const data ={
name:'pink'
}
//对对象进行字符串转换
let str = JSON.stringify(data)
// response.send();只支持两种数据类,一种是二进制,一种是字符串
//设置响应体
response.send(str)
//引入express
const express = require('express')
// 创建应用对象
const app =express()
// 创建路由规则
app.all('/json-server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//响应头
response.setHeader('Access-Control-Allow-Headers','*')
//响应一个数据
const data ={
name:'pink'
}
//对对象进行字符串转换
let str = JSON.stringify(data)
// response.send();只支持两种数据类,一种是二进制,一种是字符串
//设置响应体
response.send(str)
});
//4.监听端口启动
app.listen(8000,()=>{
console.log(
"服务已经启动了,8000端口监听中..."
)
})
客户端
客户端接收我们想要获取里面的数据有两种方法
第一种:手动转换数据
//手动对数据转化
let data =JSON.parse(xhr.response);
第二种:设置响应体的数据类型
//设置响应体数据的类型
xhr.responseType ='json'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #903;
}
</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
//1.手动对数据转化
// let data =JSON.parse(xhr.response);
// console.log(data)
// result.innerHTML = data.name
//2.自动转换
console.log(xhr.response)
result.innerHTML = xhr.response.name
}
}
}
}
</script>
</body>
</html>
如有不正确,期待指正!!!