使用express框架建立服务器
在项目中建立server.js代码
1.引入exress
const express = require('express');
2.创建应用对象
const app = express();
3.创建路由规则
request是对请求报文的封装
response 是对响应报文的封装
app.get('/server',(request,response)=> {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('Hello Ajax');
});
app.post('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('Hello World');
});
4.监听端口启动服务
app.listen(8083,()=>{
console.log("服务已经启动,8083 端口监听中...");
})
在项目中建立Post.html
<!DOCTYPE html>`在这里插入代码片`
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Post 请求</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #903;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取元素对象
const result = document.getElementById("result");
//绑定事件
result.addEventListener("mouseover",function(){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.设置类型与URL
xhr.open('POST','http://127.0.0.1:8083/server');
//3.发送
//post设置请求体
xhr.send('a=100&b=200&c=300');
//4.事件绑定
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <300){
//处理服务端返回的结果
result.innerHTML = xhr.response;
}
}
}
});
</script>
</body>
</html>
使用node.js进行服务的启动
node server.js
使用vscode进行项目的访问,把鼠标移动到矩形框中会出现HelloWorld字眼
查看浏览器的F12控制台会出现server请求,server请求的状态码为200表示请求成功。