问题描述
我想在 Auth token
标头选项中异步生成一个 gatsby-source-graphq
。根据文档,我可以使用异步函数来生成我的 Bearer token
,但我也想将它存储在某个地方。我无法使用 sessionStorage
或 localStorage
,因为我无权访问 gatsby-config.js
中的 window 对象。有没有办法实现这一目标?这是我的代码:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,});
const axios = require("axios");
const getAuthToken = async () => {
const token = btoa(
`${process.env.CTP_CLIENT_ID}:${process.env.CTP_CLIENT_SECRET}`
);
try {
const { data } = await axios.post(
// I would like to save the Auth token here
`${process.env.CTP_AUTH_URL}/oauth/token?grant_type=client_credentials`,null,{
headers: {
Authorization: `Basic ${token}`,},}
);
return `Bearer ${data.access_token}`;
} catch (err) {
console.warn(err);
}
};
module.exports = {
siteMetadata: {
siteUrl: "https://www.yourdomain.tld",title: "test_shop",plugins: [
"gatsby-plugin-typescript","gatsby-plugin-postcss","gatsby-plugin-image",{
resolve: "gatsby-plugin-google-analytics",options: {
trackingId: "test_shop","gatsby-plugin-react-helmet","gatsby-plugin-sharp","gatsby-transformer-sharp",{
resolve: "gatsby-source-graphql",options: {
// Arbitrary name for the remote schema Query type
typeName: "Merchant",// Field under which the remote schema will be accessible. You'll use this in your Gatsby query
fieldName: "merchant",// Url to query from
url: "https://api.europe-west1.gcp.commercetools.com/wj_trial/graphql",// Todo: add token dynamically
headers: async () => {
return {
Authorization: await getAuthToken(),};
},{
resolve: "gatsby-source-filesystem",options: {
name: "images",path: "./src/images/",__key: "images",],};
解决方法
我不认为这是可以实现的,也不是一个好的选择。事实上,您正在 SSR 中获取您的令牌(当 gatsby-source-graphql
被触发时),正如您所指出的,您没有任何可用于存储响应的工具。在构建/部署项目时,您(或您的公司/客户)将始终触发此操作。
在您的客户端(任何 React 组件)中,您知道任何 AJAX 操作都将由用户或您的应用程序的任何副作用触发,在那里您可以控制环境,对我来说,这是您应该将您的令牌、凭据等保存在 cookie、localStorage
等中。
混合两种令牌是不同的情况,我认为这不是一个好的选择,因为它有自己的行为(在项目构建时触发与由客户端触发)。
因此,回答您的问题时,您应该复制该部分代码(将其隔离到一个单独的函数中,并在需要时调用两次)。