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

全局拦截 #20

Closed
jechtliu opened this issue Jun 28, 2019 · 1 comment
Closed

全局拦截 #20

jechtliu opened this issue Jun 28, 2019 · 1 comment
Labels
good first issue Good for newcomers

Comments

@jechtliu
Copy link

能否提供一下全局拦截的例子?

@NewFuture
Copy link
Owner

NewFuture commented Jun 28, 2019

为所有的默认请求注入一个认证的 Authorization

import { REQUEST, transformRequestSendDefault } from "miniprogram-network";

// 同步方式
REQUEST.Defaults.transformSend = (options) => {
    options.headers["Authorization"] = `brearer ${getAuthToken()}`; // 更安全的做法应该检查一下 headers 是否存在
    return transformRequestSendDefault(options); // 剩下数据使用默认转换转换成wx.request的标准格式
};

// 异步方式 (promise 也可) 
REQUEST.Defaults.transformSend = async (options) => {
    const token = await getAuthTokenPromise(); // 异步方法
    options.headers["Authorization"] = `brearer ${token}`;
    return transformRequestSendDefault(options);
};

@NewFuture NewFuture added the good first issue Good for newcomers label Jun 29, 2019
@jechtliu jechtliu closed this as completed Jul 1, 2019
@NewFuture NewFuture pinned this issue Aug 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants