我想知道如何像在axios中那样,将应用程序凭证(甚至是用户凭证通过代码)传递到apollo客户端。
在 axios 中 -
const data = await axios({
method: "POST",
url: `${SOME_URL}`,
auth: {
username: USER, //like this//
password: PASS,
},
data: req.body,
headers: { Accept: "application/json" },
});
在apollo客户端中,我使用了apollo-link-http,我的设置是这样的---。
import fetch from "unfetch";
import { ApolloClient } from "apollo-client";
import { from } from "apollo-link";
import { onError } from "apollo-link-error";
import { createHttpLink } from "apollo-link-http";
const client = new ApolloClient({
link: from([errorLink, standardVariablesLink, typenameCleanerLink, createHttpLink({ uri: "https://graphql-backend/graphql", fetch })]),
cache,
});
我曾试过添加 全权证书选项 在createHttpLink对象中作为 credentials:
${USER}:${PASS}
或作为一个对象
credentials: {
user: USER,
password: PASS
}
但没有用。
任何帮助感谢。谢谢!
这是什么?auth
在轴心? ......搜索了一下。基本认证 options! axios
内部转换为header。
Apollo客户端就没那么好了......你需要自己把params转换成header,然后用这种方式。
const link = createHttpLink({
headers: {
authorization: "Basic btoa_converted_username_password";
},
这个... auth
选项中 axios
只是一种速记的方式来构造一个 基本授权头. 为了构建要包含在头中的凭证值,你可以做以下工作。
- 用户名和密码用冒号(aladdin:opensesame)组合。
- 所得到的字符串是base64编码的(YWxhZGRpbjpvcGVuc2VzYW1l)。
所以你可以做这样的事情。
createHttpLink({
uri: '...',
headers: {
Authorization: `Basic ${window.btoa(`${username}:${password}`)}`,
}
})
如果你是在Node.js中运行这段代码,你可以用下面的代码来代替: btoa
:
Buffer.from(`${username}:${password}`).toString('base64')
还要注意的是,如果这段代码是在客户端运行的,你可能会想通过使用以下方法动态注入头文件 设置上下文 而不是。