nodejs 和 axios 在前后端http交互中的拦截器原理和实现(一)

axios学习笔记 axios,基于ES6规范下Promise对象的AJAX异步请求框架。 阅读详情

nodejs 和 axios 在http交互中的简易拦截器(一)

nodejs –> 基于谷歌V8引擎,使用javascript编程实现的一个web服务端编程语言
axios –> 基于ES6新语法promise的一个前端ajax库
拦截器 –> 对特定的http请求或响应消息或请求头进行验证,拦截不合法的http交互以保证web环境的安全

引入

  • 先从我为什么要写这个无聊又没有挑战的拦截器开始说吧。昨天一同学问了我一个问题:“诶,大哥啊,你那个后台管理系统demo为什么要设置拦截器,这个拦截器是干嘛用的?”
  • 我的回答很简单,因为这个问题实际上真的很简单:“拦截器就是在你的请求要做接下来的处理时,多一次或多次验证。例如:你写了几个请求数据的接口,开启服务后,用户没登录直接访问这些接口,也是可以拿到数据的,但这就违背了后台管理系统必须先登录的原则,有心人就会利用这个bug来窃取你的数据库数据了”
  • 说白了,拦截器就是起一个拦截作用嘛
  • 说到这里,左前后端交互的同学们都注意了哈,前后台交互一定要遵循一个原则:互不信任原则。怎么说呢,就是前端发送到后台的参数(必须在前端验证合法的才能发送),后台必须验证是否合法(是否符合该参数的原定数据类型和值范围),后台返回给前端的数据,也必须验证是否为约定的数据结构和值类型。

进入正题 —- 前端的拦截器原理和实现

  • 上面也说到了,拦截器就是在你的请求要做接下来的处理时,多一次或多次验证。先看一段示例:前端的拦截器怎么写(这里引用第三方的ajax库 –> axios,其他ajax库可参考)
    // http请求拦截
    axios.interceptors.request.use(config => {
        if (config.method == 'post' && config.url != '/login') {
            config.data = {
                ...config.data,
                ...{"user": "admin"},
                ...{ "datetime": new Date() }
            }
        } else if (config.method == 'get') {
            if (/\?/.test(config.url)) {
                config.url += 'user=admin&datetime=' + new Date();
            } else {
                config.url += '?user=admin&datetime=' + new Date();
            }
        }
        return config;
    });
    // http响应拦截
    axios.interceptors.response.use(response => {
        switch (response.data.requestIntercept) {
            case 1:
                console.log('登录信息已失效,请重新登录!');
        }
        return response;
    });
  • 这个示例中设置了前端向服务端发起请求时的http请求拦截和服务端返回数据时的http响应拦截,interceptors是axios的一个拦截器对象,axios.interceptors.request是对http请求拦截配置的对象,这里我设置了给每个请求添加一个系统当前的时间和一个用户名(实际项目中添加用户名变量),这样可以避免get请求出现304,并且每次发起请求都向服务器发送一次用户名,axios.interceptors.response是对http响应拦截配置的对象,这里如果服务器返回json为{requestIntercept: 1},则判定服务器拒绝了页面的http请求的执行,直接返回一个状态提示,否则就返回正常的 response。
  • 前端这样设置了拦截器就一劳永逸了吗?当然不是的,前端的永远不是安全的

安全级别的拦截器 —- nodejs服务端的拦截器原理和实现

  • 服务端的拦截器才是安全的,先看下面这段简单的拦截器代码,主要拦截的是没有用户名或有用户名但在服务端没有对应的session的http请求
    // 拦截器
    app.all('/*', function (req, res, next) {
        if (req.url == '/login') {
            next();
        } else {
            if (req.method == "GET") {
                username = req.query.user;
            } else if (req.method == "POST") {
                username = req.body.user;
            }
            if (sessionPool[username] && getSid(res.req.headers.cookie) == sessionPool[username]) {
                // 用户session存在
                next();
            } else {
                res.json({ requestIntercept: 1 });  // 页面拿到这个值在做拦截处理即可
            }
        }
    });
  • app.all(‘/*’),这里的app是 express() 对象,app.all() 是针对所有的http请求, ‘/*’匹配的是所有以“/”开头的http请求,后面执行的实际上相当于是一个接口,三个参数分别是request,response,next,其中next是拦截器通过的回调函数
  • 这里的思路就是先判断请求是否为登录接口,不是的话就取出请求中的user参数,用这个user去验证两边的cookie是否相同,若不同则直接返回{ requestIntercept: 1 }这个json,告诉前端验证不通过;验证通过的调用next()回调函数进入下一个处理环节 — 数据读取接口

完整的前后端交互拦截器示例:

  • 完整的拦截器设置:(以 /getlist 接口为例)

    1. 前端发起/getlist 接口的http请求,拦截并验证请求
    2. 服务端通过app.all(‘/*’),匹配到/getlist 接口是 /* 开头的请求,立即拦截/getlist 接口的http请求并验证
    3. 验证通过后,调用next()方法将后续处理交给 app.('/getlist') 处理
    4. app.('/getlist') 处理完成后返回数据给前端
    5. 前端验证返回的json数据是不是{requestIntercept: 1},若不是则交给 axios.post('/getList').then() 处理,至此一次http请求完成,若返回的json数据是{requestIntercept: 1},那么在 axios.interceptors.response 就会被拦截,同时会告知axios.post('/getList') 对象将promise对象的状态由 pending(promise正在异步执行中) 改为 resolved(promise执行完毕)
  • 前端: index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>login</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            input {
                -web-kit-appearance: none;
                -moz-appearance: none;
                font-size: 1.4em;
                height: 2em;
                margin: 0.5em 0;
                border-radius: 4px;
                border: 1px solid #c8cccf;
                color: #6a6f77;
                outline: 0;
            }
            input:focus {
                border: 1px solid #ff7496;
            }
            input[type="button"]:focus {
                background-color: #999999;
            }
            .login-form {
                width: 25%;
                margin: 100px auto;
                line-height: 3em;
            }
            .login-form input,
            .login-form button {
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="app" class="login-form">
            <input type="username" v-model="user">
            <input type="password" v-model="pwd">
            <input type="button" value="登录" @click="login">
            <input type="button" value="获取数据" @click="getList">
            <input type="button" value="注销" @click="logout">
        </div>
        <script type='text/javascript' src='./js/vue.min.js'></script>
        <script src="https://cdn.bootcss.com/axios/0.16.2/axios.min.js"></script>
        <script type='text/javascript'>
            // http请求拦截
            axios.interceptors.request.use(config => {
                if (config.method == 'post' && config.url != '/login') {
                    config.data = {
                        ...config.data,
                        ...{ "user": "admin" }
                    }
                } else if (config.method == 'get') {
                    if (/\?/.test(config.url)) {
                        config.url += 'user=admin'
                    } else {
                        config.url += '?user=admin'
                    }
                }
                return config;
            });

            // http响应拦截
            axios.interceptors.response.use(response => {
                switch (response.data.requestIntercept) {
                    case 1:
                        console.log('登录信息已失效,请重新登录!');
                }
                return response;
            });
            let Vm = new Vue({
                el: '#app',
                data() {
                    return {
                        user: 'admin',
                        pwd: 'admin'
                    }
                },
                methods: {
                    login() {
                        const that = this;
                        axios.post('/login', {
                            "user": that.user,
                            "pwd": that.pwd
                        }).then((res) => {
                            console.log(res.data);
                            if (res.data.status == 1) {
                                alert('登陆成功!');
                            }
                        }).catch((err) => {
                            console.log('出错了-,-!', err);
                        })
                    },
                    getList() {
                        axios.post('/getList', {
                            // "user": "admin"
                        }).then((res) => {
                            console.log(res.data);
                        }).catch((err) => {
                            console.log('出错了-,-!', err);
                        })
                    },
                    logout() {
                        axios.post('/logout', {
                            // "user": "admin"
                        }).then((res) => {
                            console.log(res.data);
                            if (res.data.logout == 1) {
                                alert('注销成功');
                            }
                        }).catch((err) => {
                            console.log('出错了-,-!', err);
                        })
                    }
                }
            })
        </script>
    </body>
    </html>
  • 服务端:app.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const fs = require('fs');
    const path = require('path');
    const mysql = require('mysql');

    const app = express();
    app.use(express.static(path.resolve(__dirname, './www')));  // 默认首页为www下的index.html
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extend: true }));

    const sessionPool = {};

    const pool = mysql.createPool({
        host: 'mysql数据库IP',
        user: 'mysql连接用户,最高权限用户为root',
        password: '填写你的密码',
        port: '数据库端口,默认3306',
        database: '使用的mysql数据库名',
        multipleStatements: true
    });

    // 拦截器
    app.all('/*', function (req, res, next) {
        let url = req.url;
        if (url == '/login') {
            next();
        } else {
            if (req.method == "GET") {
                username = req.query.user;
            } else if (req.method == "POST") {
                username = req.body.user;
            }
            if (sessionPool[username] && getSid(res.req.headers.cookie) == sessionPool[username]) {
                // 用户session存在
                next();
            } else {
                res.json({ requestIntercept: 1 });  // 页面拿到这个值在做拦截处理即可
            }
        }
    });

    // 请求错误
    app.get('/error', function (req, res) {
        res.send(fs.readFileSync(path.resolve(__dirname, './www/error.html'), 'utf-8'))
    });

    // 测试接口
    app.get('/', function (req, res) {
        res.json({ test: `测试服务器正常!` });
    })

    // 登录接口
    app.post('/login', function (req, res) {
        // 判断是否已在线
        if (sessionPool[req.body.user]) {
            // 在线
            delete sessionPool[req.body.user];
        }
        // 使用数据库连接池
        pool.getConnection(function (err, connection) {
            // 多语句查询示例
            connection.query("select * from userlist where username = '" + req.body.user + "' and password = '" + req.body.pwd + "' and delMark = '0'; select count(1) from userlist", function (err, rows) {
                if (err) {
                    throw err;
                } else {
                    if (rows[0].length > 0) {
                        // 设置cookie
                        let cookieSid = req.body.user + Date.parse(new Date());
                        res.setHeader("Set-Cookie", ["sid=" + cookieSid + ";path=/;expires=" + new Date("2030")]);
                        // 先存储session到sessionPool
                        sessionPool[req.body.user] = cookieSid;
                        // 返回登录成功的信息
                        res.json({ status: 1, dbData: rows[0], session: req.session });
                        res.end();
                    } else {
                        // 用户不存在
                        res.json({ status: 0 });
                        res.end();
                    }
                }
            });
            // 释放本次连接
            connection.release();
        });
    })

    // 退出登录
    app.post('/logout', function (req, res) {
        delete sessionPool[req.body.user];
        res.json({ logout: 1 });
        res.end();
    })

    app.post('/getList', function (req, res) {
        pool.getConnection(function (err, connection) {
            connection.query('select * from userlist', function (err, rows) {
                if (err) {
                    throw err;
                } else {
                    res.json({ list: rows });
                    res.end();
                }
            });
            connection.release();
        })
        console.log('session池 ', sessionPool);
    });

    app.listen(8000, function () {
        console.log('ssh@git 0.0.0.0:8000 succeed');
    })

    /*
    * 公共方法
    */

    // 解析cookie中的sid
    function getSid(cookieStr) {
        let sid = '', cookieArr = cookieStr.split(';');
        for (let i = 0; i < cookieArr.length; i++) {
            if (cookieArr[i].trim().substring(0, 3) == 'sid') {
                return sid = cookieArr[i].trim().substring(4, cookieArr[i].length);
            }
        }
        return sid;
    }
25.前端axios拦截器 一刷新前端报错了,以前我们登录成功了也不需要校验,要数据后端就给我们,现在不行了,必须传入token,那现在我们哪有token值,因为我们要请求一些数据,所以直接请求的话就报401错误,也就是我们在后端自己写的,现在我们后端改好了,前端还没开始。从前端发起的所有axios请求都应该携带上我们的token,而这个token是在我们登入成功之后就应该拿到的。后端使用了拦截器,我们前端也有类似于发请求的拦截器,那就是使用第三方的库axios。axios的好处就是它的封装性、使用便利。 阅读详情

相关推荐

Vue3进阶使用详解(node.js、Vue3路由基础项目、axios的使用详细(实现数据分页---前后端分离)、axios加载失败)

导入axios的代码放置的位置为:原因:一般情况下如果是第一次使用vue3且第一次导入会有一个问题:这样就能够解决axios导入的错误。 安装的过程是全程点击下一步,除了安装时要选择自己的安装路径(选择安装在c/d盘外) node: 进入node.js环境 npm:安装模块 打开cmd终端输入:node -v 测试能否打印node.js的版本号:如下图表示已经安装成功:

m0_56245143的博客 2935

Nodejs axios模块使用整理

支持PromoisAPI,支持拦截请求和响应,支持转换请求和响应数据,支持取消请求,支持自动转换JSON数据,支持客户端防御XSRF。Axios是一个基于Promise网络请求库,可以用于node.js 环境和浏览器环境使用。在node.js框架中封装http模块,在浏览器中分装XMLHttpRequests对象。这些属性都不必在配置中指定。类似$.ajax()1.nodejs 使用。1. 发送get请求。2.发送多个并发请求。

天马3798 7741

若依SSO OAuth2环境配置全攻略:从零搭建统一登录认证中心

在多个业务系统并存的场景下,用户重复登录的痛点催生了单点登录(SSO)的需求。SSO通过统一的认证中心管理用户身份,而OAuth2协议则定义了授权码、令牌等标准化交互流程,让各业务系统无需接触用户密码即可安全完成身份验证。理解授权码模式的工作原理,是搭建基于若依框架的SSO环境的基础。本文聚焦于ruoyi-sso-oauth2的环境配置环节,系统梳理JDK、Maven、MySQL、Redis、Node.js等核心组件的版本选型与配置要点,并针对数据库连接、Redis缓存、回调地址等常见坑点给出排查思路。无论

weixin_34160277的博客 612

前端开发-拦截器

请求拦截器和响应拦截器的作用.

Wsnbb007的博客 2845

HTTP连接池优化:解决AI服务高并发超时与性能瓶颈

HTTP连接池是提升网络应用性能的核心技术之一,其原理在于复用已建立的TCP连接,从而避免频繁的TCP三次握手与TLS握手带来的开销。这项技术的核心价值在于显著降低延迟、提升吞吐量,并节约系统资源。在工程实践中,尤其是在高频调用外部API(如AI服务)的场景下,合理配置连接池是保障服务稳定性的关键。通过精细化管理连接池大小、超时与重试策略,可以有效应对高并发请求,避免端口耗尽和请求排队问题。本文以优化DeepSeek API调用为例,深入探讨了在Python与Node.js环境中配置连接池、实现TLS会话复

weixin_34198453的博客 412

10-前端添加拦截器

1、所有的请求头添加token,token过期、没有token的响应统一添加报错提醒,跳转到登录页面。在ticketweb/src/main.js文件。

NikoChina的博客 579

一步一步解析Axios源码,从入门到原理

一. Axios是什么?一个基于 Promise来管理http 请求的简洁、易用且高效的代码封装库。通俗一点来讲,它是一个前端替代Ajax的一个东西,可以使用它发起...

全栈者 的博客 5706

802.1x之EAP-TLS测试方法

CA证书一般是由权威的认证机构发出,用来验证该机构签名的证书,持有CA证书的设备可以验证对端的证书是否由自己信任的机构颁发的。在我们内部使用证书时,我没可以自己充当CA认证机构,管理私钥和CA证书,使用他们签名服务器、客户端证书。2、使用证书请求文件server_csr.pem、CA私钥、CA公钥生成服务器证书(正常情况下自己不拥有CA私钥,是把证书请求文件发给认证机构,由认证机构返回证书)进行802.1x EAP-TLS认证时需要IPC、服务器分别存储CA证书、设备证书、私钥,通过交换证书实现身份验证。

写作是为了更好的思考 2166

nodeJS--axios和fetch

简单来说:axios就是将原生AJAX进行封装,使用Promise实现的,它会生成Promise对象,方便我们进行网络请求的一种工具;使用时需要导入axios.js。封装原理代码看之前写的。

qq_56973906的博客 1811

不修改MMDetection源码使用自定义数据和模型

以目标检测为例,用非侵入式的模型和MMDetection数据的方法进行配置。也就是不改动MMDetection的任何源码或目录的条件下,使用自定义数据训练自定义模型。

Dlite的技术笔记 1345

利用GBD数据库做未来疾病负担预测

最近看到一篇文献,利用GBD数据库中的数据对疾病负担的发展趋势进行预测。觉得很有趣,就抽空用R语言复盘了一下里面关键的方法。 参考文献: Changing trends in the disease burden of esophageal cancer in China from 1990 to 2017 and its predicted level in 25 years DOI: 10.1002/cam4.3775 1. 相关R包的安装 主要用到的R包有3个,一个一个讲: 1.1 Nordpred

NickyCat的博客 5万+

安装axios_一步一步解析Axios源码,从入门到原理

一. Axios是什么?一个基于 Promise来管理http 请求的简洁、易用且高效的代码封装库。通俗一点来讲,它是一个前端替代Ajax的一个东西,可以使用它发起http请求接口功能,它是基于Promise的,相比于Ajax的回调函数能够更好的管理异步操作。二. Axios的特点三. 安装Axios1、通过使用npm命令安装它。npm i axios --save2、 安装成功...

weixin_39801165的博客 271

从AMBA到USB:手把手教你评估和选择Synopsys DesignWare里的免费商用IP

本文详细介绍了如何评估和选择Synopsys DesignWare中的免费商用IP,从AMBA到USB等关键模块。通过技术参数核对、验证环境评估和集成注意事项,帮助工程师高效利用这些经过硅验证的商业级IP,提升SoC设计效率。文章还探讨了免费IP与付费IP的边界策略,避免常见陷阱。

weixin_42683394的博客 300

axios 一个基于promise的HTTP库

特征 从浏览器中创建XMLGHTttpRequests对象 从nodejs中创建http请求 支持PromiseAPI 拦截请求和响应 转换请求数据和响应数据 取消请求 自动转换JSON数据 客户端支持防御XSRF XSS(跨站脚本)和CSRF(跨站请求伪造) 用户输入总是不可信任的 不攻击服务器端而攻击正常访问网站的用户 XSS: 往Web页面里插入恶意Script

Tan_D的博客 1879

【Pytorch教程】:卷积神经网络 CNN

Pytorch教程目录 Torch and Numpy 变量 (Variable) 激励函数 关系拟合(回归) 区分类型 (分类) 快速搭建法 批训练 加速神经网络训练 Optimizer优化器 卷积神经网络 CNN 目录Pytorch教程目录什么是卷积神经网络 CNN卷积 和 神经网络池化(pooling)流行的 CNN 结构CNN 卷积神经网络MNIST手写数据CNN模型训练可视化训练全部代码 什么是卷积神经网络 CNN 卷积 和 神经网络 卷积神经网络是如何运作的呢, 举一个识别图片的例子, 我们知

nanke_4869的博客 8106

基于深度学习的心律失常的自动分类

基于深度学习的心律失常的自动分类 作者:禅与计算机程序设计艺术 1. 背景介绍 1.1 心律失常的危害与检测的重要性 心律失常是一种常见的心血管疾病,严重威胁着人们的健康和生命。据统计,全球每年有数百万人因心律失

AI架构师小马 1149

axios

axios 是什么? Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。前端最流行的 ajax 请求库, react/vue 官方都推荐使用 axios 发 ajax 请求… axios 特点 基于 promise 的异步 ajax 请求库,支持promise所有的API 浏览器端/node 端都可以使用,浏览器中创建XMLHttpRequests 支持请求/响应拦截器 支持请求取消 可以转换请求数据和响应数据,并对响应回来的内容自动转换成 JSON类型的

codewhy的博客 192

YOLO11涨点优化:原创自研 | 魔改Bottleneck,具备多尺度和特征通道融合的结构

可以将C3k2_MSAMCS放在neck,或者backbone和neck同时修改,具体看自己数据集的涨点情况决定

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 1653

NodeJS全栈开发面试题讲解——P4前后端协作与接口设计

问题编号涉及知识点4.1RESTful 设计、状态码规范4.2跨域原理、服务端 CORS 设置4.3Token 过期检测、刷新机制4.4登录注册流程、验证码、加密与鉴权4.5联调常见问题排查与实践经验。

Theoweb3|优快云 wwh1st|GitHub theoweb3|TG theo_liu|X theoweb33|gmail wwh9th 华语区Web3基础设施建设者;Web3开源社区共建者;博客沉淀去中心化等各类工程经验。 1174

使用verilog实现基于FPGA的TDC设计

verilog实现TDC 高精度时间数字转换器概述(TDC) 简介: TDC被用于测量时间间隔,应用在物理研究、飞行时间测量领域等。 本设计使用verilog实现并在xilinx和altera的FPGA上均可实现! 设计中使用到下述几个模块,包括FIFO,COUNT等,在xilinx下也使用到了一些原语等。下面有实现的代码和仿真截图等。 顶层模块设计如下: module top( input wire start, input wire stop, input wire clk, output wire T

QQ_778132974的博客 6254

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

尚硅谷 Ajax与Axios的使用与关键源码 笔记

文章目录Ajax概述原生Ajax尝试请求的发送与请求头配置JSON支持IE缓存问题请求的取消与重发jQuery的Ajax使用Axios发送Ajax[简易]使用fetch发送请求Ajax跨域JSONP解决跨域问题CORS解决跨域问题Axios的理解与使用JSON Server的使用Axios基本使用拦截器取消请求Axios源码分析目录结构实现axios,使得既可以axios()也可以axios.xx()Axios类的实现手写一个简易版的axios请求发送函数请求取消函数总结(八股) Ajax概述 Ajax简介

LiuKairui的博客 1125

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

axios不发起请求_一步一步解析Axios源码,从入门到原理

一. Axios是什么?一个基于 Promise来管理http 请求的简洁、易用且高效的代码封装库。通俗一点来讲,它是一个前端替代Ajax的一个东西,可以使用它发起http请求接口功能,它是基于Promise的,相比于Ajax的回调函数能够更好的管理异步操作。二. Axios的特点三. 安装Axios1、通过使用npm命令安装它。npm i axios --save2、 安装成功...

weixin_36202603的博客 358

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

nodejs做服务端多功能的简单实现

nodejs 做服务端基本功能实现http服务 express 模块 数据库服务 mysql模块 UDP消息下发和接收 dgram 模块 websocket实现 websocket服务,实现简单的聊天服务器和页面数据实时刷新

我走过最长的路,就是这条爬坑之路!!! 2258

Nodejs生成JWT Token并在Vue中携带token发起请求

文章目录1.Token简析2. JWT简析3.在Nodejs生成JWT Token 1.Token简析 Token 本质是字符串,用于请求时附带在请求头中,校验请求是否合法及判断用户身份。 Token 与 Session、Cookie 的区别: Session 保存在服务端,用于客户端与服务端连接时,临时保存用户信息,当用户释放连接后,Session 将被释放; Cookie 保存在客户端,当客户端发起请求时,Cookie 会附带在 http header 中,提供给服务端辨识用户身份; Token

鸭绒的博客 1573

前端开发者的代理世界:Node.js中的代理使用指南

想象一下,你要和外国朋友交流,但你们语言不通,这时候你需要一个"翻译官"来帮助沟通。解决跨域问题:让前端可以访问不同域名的API统一接口管理:将多个后端服务统一到一个入口开发环境优化:在本地开发时模拟生产环境请求转发:将请求转发到不同的服务器fill:#333;color:#333;color:#333;fill:none;前端应用代理服务器API服务器1API服务器2第三方服务});// 错误处理console.error('❌ 代理错误:', err.message)

2504_92236314的博客 921

【SPA项目的Jwt安全验证】

目录前言Jwt与传统的安全验证Jwt方案的处理前端对Jwt的处理后端对Jwt的处理Jwt方案测试关闭Jwt方案测试开启Jwt方案测试总结 前言 如题,Jwt也就是当下在跨域的身份验证的最好用的解决方案。 为什么在SPA中我们需要用到Jwt的一个身份验证呢? 因为如今的SPA项目是前后端分离的,所以以前的方法已经不够使用,需要用到其他的解决方案。 Jwt与传统的安全验证 一,传统的身份验证 记得...

旺旺的博客 631
上一篇: ES6学习之路~~Symbol:独一无二的值类型
下一篇: nginx 安装、配置、负载均衡、反向代理<一>
EricLua
博客等级 码龄10年 34粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值