Node.js 创建HTTP服务器和GET/POST请求
2023-09-11 14:21:07 时间
Node.js自带的http模块可以创建服务器,也可以发送GET和POST请求。
一、创建服务器
使用http.createServer()方法创建服务器,使用listen方法绑定端口3000。
通过req, res参数来接收和响应数据。
//httpserver.js const http = require('http'); const url = require("url"); const util = require('util'); const querystring = require('querystring'); const port = 3000; http.createServer((req, res) => { res.statusCode = 200, res.setHeader('Content-Type', 'text/plain;charset=utf-8'); if(req.method === 'GET') { toGet(req, res); }else if(req.method === 'POST') { toPost(req, res); } }).listen(port, () => { console.log(`Server listening on: http://localhost:${port}`); }); //获取GET请求内容 function toGet(req, res){ let data = 'GET请求内容:\n' + util.inspect(url.parse(req.url)); res.end(data); console.log(data); } //获取POST请求内容、cookie function toPost(req, res){ // 定义了一个data变量,用于暂存请求体的信息 let data = ''; // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中 req.on('data', function(chunk){ data += chunk; }); // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。 req.on('end', function(){ //data = querystring.parse(data); //res.end('POST请求内容:\n' + util.inspect(data)); data = 'POST请求内容:\n' + data; res.end(data); console.log(data); console.log('cookie内容:\n' + req.headers.cookie); }); }
在命令行提示符窗口运行node httpserver.js启动
>node httpserver.js
Server listening on: http://localhost:3000
二、发送GET请求
//httpget.js const http = require('http'); const options = { host: 'localhost', port: 3000, path: '/test?id=1', method: 'GET' }; const req = http.request(options, res => { console.log(`状态码: ${res.statusCode}`); res.on('data', d => { process.stdout.write(d); }); }); req.on('error', error => { console.error(error) }); req.end();
打开一个新的命令行提示符窗口运行node httpget.js
>node httpget.js 状态码: 200 GET请求内容: Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?id=1', query: 'id=1', pathname: '/test', path: '/test?id=1', href: '/test?id=1' }
三、发送POST请求,带cookie
//httppost.js const http = require('http'); const cookie = 'id=1;name=lc;'; const data = JSON.stringify({ name: 'lc' }); const options = { host: 'localhost', port: 3000, path: '/test2', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length, 'Cookie': cookie } }; const req = http.request(options, res => { console.log(`状态码: ${res.statusCode}`); res.on('data', d => { process.stdout.write(d); }); }); req.on('error', error => { console.error(error); }); req.write(data); req.end();
打开一个新的命令行提示符窗口运行node httppost.js
>node httppost.js 状态码: 200 POST请求内容: {"name":"lc"}
服务器的命令行提示符窗口输出:
POST请求内容: {"name":"lc"} cookie内容: id=1;name=lc;
使用supervisor自动重启服务器
上面服务器端httpserver.js代码每次有改动,都需要Ctrl+C退出再重新node httpserver.js运行,这是因为Node.js在第二次后访问的是内存,避免重复载入。
解决方法是使用npm安装supervisor,它会监视对代码的改动并自动重启Node.js。
npm install -g supervisor
启动服务器改为使用:
supervisor httpserver.js
相关文章
- JS框架_(JQuery.js)绚丽的3D星空动画
- JS框架_(JQuery.js)网页文字评论弹幕
- Node.js模块封装及使用
- WebStorm配置Node.js IDE
- Node.js包的依赖及版本号(转)
- [Node.js] process.nextTick for converting sync to async
- [Node.js] Availability and Zero-downtime Restarts
- [Tools] Create a Simple CLI Tool in Node.js with CAC
- [Node.js] Level 1 new. Intro the Node.js
- common.js
- js右键菜单
- Node.js is the perfect choice for real-time application development
- 我为什么选择采用node.js来做新一代的EasyDarwin RTSP开源流媒体服务器
- [Node.js] Add node.js command line to global
- [Cycle.js] Fine-grained control over the DOM Source
- [Whole Web, Node.js, PM2] Configuring PM2 for Node applications
- node.js常见的一些错误信息
- 从vue-cli2.x升级到@vue/cli 4.x(node v14.15.0 / vue.js 3.0)
- UI5 repository mapping and Component-preload.js UI5RepositoryPathMapping.xml
- Atitit 多线程 什么时候使用多进程的选择场景 目录 1.1. 看实现,比如你的用node.js实现,那就没得选了,只能多进程1 1.2. 如果用java这一类,可以选择多进程与多线程模式,或
- 华为OD机试 - 最优资源分配(Java & JS & Python)
- 一文搞懂如何使用Node.js进行TCP网络通信
- EazyUI主页框架搭建纯JS样例
- Node.js: node-redis.js客户端
- Node.js学习笔记(二)——Node.js模块化、文件读写、环境变量
- JS中axios使用注意点
- Node.js,快速启动一个web服务,临时服务anywhere
- Node.js(一)概述、全局对象/函数、node各模块使用介绍
- 2021前端常见面试题必考必问:js中 非==和 非=的区别是什么?js中==和===区别?
- JS &&(与运算)详解
- JS从0到1——808. 最大公约数