我想知道如何将应用程序凭据(甚至是用户凭据通过代码)传递给阿波罗客户端,就像我们在axios中所做的那样。
在公理中-
const data = await axios({
method: "POST",
url: `${SOME_URL}`,
auth: {
username: USER, //like this//
password: PASS,
},
data: req.body,
headers: { Accept: "application/json" },
});对于阿波罗客户,我用过阿波罗-链接-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
}但那不管用。
任何帮助都很感激。谢谢!!
发布于 2020-06-12 16:36:01
问题:
auth in axios? .搜索:basic auth options!axios内部将其转换为标头。
阿波罗的客户不是很好..。您需要将params转换为标头本身,并使用以下方式:
const link = createHttpLink({
headers: {
authorization: "Basic btoa_converted_username_password";
}, 发布于 2020-06-12 16:40:27
auth选项在axios中只是构造基本授权头的一种简单方法。为了构造要包含在标题中的凭据值,您可以执行以下操作:
所以你可以做这样的事情:
createHttpLink({
uri: '...',
headers: {
Authorization: `Basic ${window.btoa(`${username}:${password}`)}`,
}
})如果您在Node.js中运行此代码,您将使用下面的代码而不是btoa
Buffer.from(`${username}:${password}`).toString('base64')还请注意,如果这段代码正在运行客户端,您可能希望使用setContext动态注入标头。
https://stackoverflow.com/questions/62347214
复制相似问题