Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

嗨!JSer,你知道拦截器(interceptor)么? #3

Open
shaodahong opened this issue Feb 28, 2017 · 3 comments
Open

嗨!JSer,你知道拦截器(interceptor)么? #3

shaodahong opened this issue Feb 28, 2017 · 3 comments
Labels

Comments

@shaodahong
Copy link
Owner

shaodahong commented Feb 28, 2017

拦截器-interceptor

在现代的一些前端框架上,拦截器基本上是很基础但很重要的一环,比如Angular原生就支持拦截器配置,Axios也给我们提供了拦截器配置,那么拦截器到底是什么,它有什么用?

拦截器字面上理解就是用来拦截的工具,一说到互联网上的拦截工具你应该立马能想到电脑的防火墙,对,拦截器的功能其实和防火墙一样,就是拦截出站和入站的规则

拦截器能帮助我们解决的

  • 添加统一的request的参数
    比如header中加入X-Requested-With,比如客户端需要实现sign和token的验证机制,比如你可以写$http.get('/files', params),拦截器帮你拼接成http://www.xxxx.com/1/files这样的请求地址
  • 处理统一的responseError
    比如重连机制,拿到error.code错误码重连,比如token过期,重新拿到token再次send request
    比如统一报错信息,给所有返回的404来个提示也会很酷
  • 等等

angular interceptor

angular的interceptor是个数组,在$httpProvider中进行配置,一般写成一个config, 然后$httpProvider注入进来就可以配置了,把我们写的interceptorpush进去就OK了,$httpProvider.interceptors.push('interceptor'),interceptor一般写成一个服务

var interceptor = {
	'request': function (config) {
		return config
	},
	'requestError': function (rejection) {
		
	},
	'response': function (response) {
		return response
	},
	'responseError': function (rejection) {

	}
}

return支持返回一个promise,可以对config中的params,data, url, headers等进行加工,符合我们的请求再return出去,所有的$http请求都会被拦截到

@leohxj
Copy link

leohxj commented Jul 6, 2019

Interceptor 和 Middleware 两者的差异能说说吗?

@shaodahong
Copy link
Owner Author

@leohxj 就是一个东西,拦截器本身就是一个中间件,比如 Axios

@rxliuli
Copy link

rxliuli commented Feb 19, 2021

虽然 axios 提供了拦截器功能,不过吾辈一般不用它,宁愿在项目中再包一层浅层封装,方便统一更新、修改和替换 o(^@^)o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants