使用express创建web服务器
使用express创建web服务器
Contents
1. 简单的express服务器
安装npm install express使用npm找不到源,改用cnpm
第一版本
var express = require('express');
var app = express();
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);
运行后,在浏览器打开localhost:18001 提示不能GET /
解决方法加入路由
var express = require('express');
var app = express();
app.get('/',function(req,res){
res.end('hello\n');
});
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);
运行后,在浏览器打开localhost:18001返回hello * 除了手写,express还提供了生成工具,
先来安装 npm install -g express-generator 如何使用 express 你的项目名字,会产生了一个目录
执行文件在bin目录下 无法运行 ,需要安装必须的包 npm install
2. 静态文件服务
使用静态文件中间件
var express = require('express');
var app = express();
app.use(express.static('public'));//public 为静态文件目录
app.get('/',function(req,res){
res.end('hello\n');
});
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);
创建静态文件 mkdir public vim public/test.txt 写入hello world
然后 使用curl http://localhost:180001/text.txt即可访问
3. 路由
分析URL: 协议 域名 目录 文件参数 http://www.baidu.com/doc/hello.txt?source=chrome&from=xxx 分析URL: 协议 域名 目录 文件参数 http://www.baidu.com/doc/hello.txt#xx xx为锚点或js路由 路由的含义 :没有扩展名的URL 不是映射到某个文件,而是主机名目录,并不是文件,可能是个处理函数 区分:路径 请求方法 来交给不同的函数
三种方法
-
path app.动词
例如 app.get
-
Router 例如
var Router = express.Router(); /** http://example.com/post/add* http://example.com/post/list* 存在公共前缀,最好用router来组织 */ Router.get('/add',function(req,res){ res.end('Router /add\n'); }); Router.get('lsit',funciton(req,res){ res.end('Router /list\n'); }); app.use('/post',Router);//第一个参数指定基础路由为post
-
route方式 针对一个路由下不同方法的处理
app.route('/article')
.get(function(req,res){
res.end('route /article get\n');
})
.post(function(req,res){
res.end('route /article get\n');
});
//测试 curl -POST htpp://localhost:180001/article
路由参数
//http://example.com/new/123
app.param('newId',function(req,res,next,newsId){
req.newsId = newsId;//URL参数中的值
next();//执行完之后调用的,即使返回给了用户数据,也会执行//打印请求日志 morgan
});
app.get('/news/:newsId',function(req,jres){
res.end('newsId: '+req.newsId+'\n');
})
4. 中间件
基于Connect。分层处理。每层使用一个功能
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?