1、express static实现静态资源
第一种 直接访问public
app.use(express.static(path.join(__dirname, '/public')))
第二种 以/public访问public
app.use('/public', express.static(path.join(__dirname, '/public')))
2、path
process.cwd()返回当前工作目录。如:调用node命令执行脚本时的目录。
当前文件的绝对路径 __filename
当前文件夹的绝对路径 __dirname
拼接路径path.join(__dirname,'index.html')
返回path的目录名
path.dirname('/目录1/目录2/目录3');
返回扩展名
path.extname('index.html');
3、url路径解析模块
var urlObj = url.parse(req.url, true);
var query = urlObj.query;
querystring.stringify()
querystring.parse();
4、params传参的形式
.get('/api/product/remove/:id', api.removeProduct);
'/api/product/remove/'+ [变量]
则req.params 获取参数
5、表单提交
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
req.body;
6、获取请求信息
req上面包含了所有的请求信息
打印一下,找到你想要的
const host = req.headers['x-forwarded-host'] || req.host;
给浏览器种cookie,可以在控制台的cookie查看
res.cookie('gpc', 'haha', {
maxAge: 0,
});
const getIP = headers => {
let ip = headers['x-real-ip'] || headers['ali-cdn-real-ip'];
if (Array.isArray(ip)) {
ip = ip[0];
}
if (!ip) {
ip = headers['x-forwarded-for'];
if (ip) {
if (ip.includes(',') && typeof ip === 'string') {
const ips = ip.split(/,\s*/);
const rIsLocal = /^(10|192\.168)\./;
if (ips.length > 1 && rIsLocal.test(ips[0]) && !rIsLocal.test(ips[1])) {
ip = ips[1];
}
ip = ips[0];
}
}
}
return ip || '';
};