【代码】Node创建简单的Web服务器 发表于 2020-09-24 更新于 2024-05-17 分类于 前端学习指北 阅读次数: 前言使用Nodejs,创建一个简单的Web服务器 源代码 创建server.js文件 正常访问1234567891011121314151617181920// 引入http模块const http = require("http");// 创建web服务器const app = http.createServer();// 设置端口app.listen(80);// 回调函数app.on("request", function (req, res) { // 获取请求的URL和请求的方法 console.log(req.url, req.method); // 200,正常访问 res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); // 设置相应内容 res.write(""); // 结束并发送响应 res.end();}); 异常访问123456789101112131415161718// 引入http模块const http = require("http");// 创建web服务器const app = http.createServer();// 设置端口app.listen(80);// 回调函数app.on("request", function (req, res) { // 获取请求的URL和请求的方法 console.log(req.url, req.method); // 404,异常访问 res.writeHead(404); // 设置相应内容 res.write(""); // 结束并发送响应 res.end();}); 重定向123456789101112131415161718// 引入http模块const http = require("http");// 创建web服务器const app = http.createServer();// 设置端口app.listen(80);// 回调函数app.on("request", function (req, res) { // 获取请求的URL和请求的方法 console.log(req.url, req.method); // 302,重定向 res.writeHead(302, { Location: "https://example.com" }); // 结束并发送响应 res.end();}); 启动项目1node server.js 完成