在这里我们继续接着之前的分享,给大家介绍node.js中的http模块
内置模块–http —创建静态服务器
本地开发常常需要搭建临时的服务,第一时间我们会想到用http-server
live-server是可以运行前端静态文件的一个服务器,既然我们要前后端分离,
所以就需要单独将html代码运行起来,
这里我们选择live-server,等到后边真正部署的时候在用nginx
在这里我们想要运行一个html文件,需要一个服务器,我们通常通过live-server插件,
live-sever的下载:我们可以通过vscode的扩展商店下载,也可以通过npm下载 ,下载后,在vscode编辑器的右下方会有Go live字样,点击就会运行当前代码
const http = require('http');
const ip = 'localhost';
const port = 8000;
const server = http.createServer((req, res) => {
res.writeHead( 200, {
'Content-type': 'text/html;charset=utf8'
})
res.write('<h3>这里是node创建的静态服务器</h3>');//这里是用来写给前端的接口数据
res.end();
}).listen(port,ip,()=>{
console.log( `The server is running at: http://${ ip }:${ port }` )
});
接下来,我们在同目录下创建一个html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$.ajax({
url: "http://localhost:8000/",//此时数据请求会出现跨域
success:function(data){
console.log(data);
}
});
</script>
//控制台的输出:
Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</body>
</html>
后端服务器有两种类型
1. web服务器 【 静态服务器 】
2. api服务器 【 暴露接口 】
解决跨域:反向代理:我们的后端帮助我们请求数据 , 在将数据发送给我们自己前端
引用express框架