1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > node.js搭建服务器

node.js搭建服务器

时间:2023-09-25 06:25:37

相关推荐

node.js搭建服务器

一、http模块

1.引入http模块

2.创建web服务器

3.监听服务器端口

const http = require("http");const app = http.createServer((req, res) => {res.setHeader("content-type", "text/html;charset=utf-8");res.end("响应成功!");});app.listen(5000, () => {console.log("服务器已启动!监听在5000端口...");});

二、静态资源服务器

const http = require("http");const fs = require("fs");const app = http.createServer((req, res) => {if (req.url == "/") {// 读取index.html页面内容let data = fs.readFileSync("./static/index.html", "utf-8");res.end(data);} else if (req.url == "/css/index.css") {// 读取index.css内容let data = fs.readFileSync("./static/css/index.css");res.end(data);} else if (req.url == "/static/img/banner02.jpg") {// 读取img内容let data = fs.readFileSync("./static/img/banner02.jpg");res.end(data);} else if (req.url == "/api") {// ajax请求res.end("success");} else {res.end("other");}});app.listen(3000, () => {console.log("服务器监听在3000端口...");});

三、服务器获取get请求参数

在./static下面写一个index.html页面,页面中发送一个get请求

const http = require("http");const fs = require("fs");const url = require("url");const qs = require("querystring");const app = http.createServer((req, res) => {console.log(req.url);if (req.url == "/") {let data = fs.readFileSync("./static/login.html");res.end(data);} else if (req.url.indexOf("/api") != -1) {console.log(qs.parse(url.parse(req.url).query));res.end("get");} else {res.end("ok");}});app.listen(8888, () => {console.log("服务器已启动!!地址为:http://localhost:8888");});

四、服务器获取post请求参数

获取post 请求的参数,通过给req绑定data事件和end事件,来获取监听的参数,data 事件一个接收的事件,end 事件 当post请求的参数都接收完毕,就出发end事件

const http = require('http');const fs = require('fs');const qs = require('querystring')const app = http.createServer((req, res) => {if (req.url == '/') {let data = fs.readFileSync('./static/login.html')res.end(data)} else if (req.url == '/api') {let str = ''req.on('data', (chunk) => {str += chunk})req.on('end', () => {// 如下就获取了post 请求提交的参数console.log(qs.parse(str)) //{ username: '张三', pwd: '111111' }})res.end('success')} else {res.end('success')}})app.listen(8888, () => {console.log('服务器已启动!!!');})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。