Reactjs Laravel灯塔当前用户通过下一个apollo为空

Reactjs Laravel灯塔当前用户通过下一个apollo为空,reactjs,laravel,apollo,laravel-lighthouse,laravel-sanctum,Reactjs,Laravel,Apollo,Laravel Lighthouse,Laravel Sanctum,我有一本带圣殿和灯塔的《拉雷维尔》的新版本。当我通过axios进行登录时,一切正常。在通过axios登录后,我添加了一个lazyquery,试图查询一些受保护的字段,但我未经验证。我不知道为什么,我已经处理了三天了。我非常感谢你的帮助 这很有效 useEffect(() => { axios.defaults.withCredentials = true; // get the token from the server axios.get(`http://api.

我有一本带圣殿和灯塔的《拉雷维尔》的新版本。当我通过axios进行登录时,一切正常。在通过axios登录后,我添加了一个
lazyquery
,试图查询一些受保护的字段,但我未经验证。我不知道为什么,我已经处理了三天了。我非常感谢你的帮助

这很有效

useEffect(() => {
    axios.defaults.withCredentials = true;
    // get the token from the server
    axios.get(`http://api.newods.test/sanctum/csrf-cookie`).then(function (resolve){
      // try login with the user
      axios.post('http://api.newods.test/api/login', {
        email: 'test@test.com',
        password: 'test'
      }).then(function (resolve) {
        console.log(`logged in ${resolve.data}`);
        axios
          .get("http://api.newods.test/api/gated", { withCredentials: true })
          .then(function (resolve) {
            console.log(`gated ${resolve.data}`);
            axios
              .get("http://api.newods.test/api/logout", {
                withCredentials: true,
              })
              .then(function (resolve) {
                console.log(`logged out ${resolve.data}`);
                axios
                  .get("http://api.newods.test/api/gated", {
                    withCredentials: true,
                  })
                  .then(function (resolve) {
                    console.log(
                      `trying to get to gated after logging out ${resolve.data}`
                    );
                  });
              });
          });
      });
    });

  }, []);
但当我把它缩短并改成这个时,我会得到未经验证的认证

const HELLO = gql\`
  query hello {
    hello
  }
`;


function Home() {

  const [hello, { loading, data }] = useLazyQuery(HELLO);

  useEffect(() => {
    axios.defaults.withCredentials = true;
    // get the token from the server
    axios.get(`http://api.newods.test/sanctum/csrf-cookie`).then(function (resolve){
      // try login with the user
      axios.post('http://api.newods.test/api/login', {
        email: 'test@test.com',
        password: 'test'
      }).then(function (resolve) {
        console.log('logged in');

      });
    });

  }, []);


  return (
    <div className="container">
      <div>Index</div>
      <button onClick={() => hello()}>
        Click to hello world
      </button>
      <p>{data && data.hello || ''}</p>
    </div>
  );
}

export default withApollo(Home);
环境署署长 config/cors.php 配置/灯塔 在我与阿波罗的下一个应用程序中

create.js 使用Apollo.js
从“React”导入React;
从“下一个/Head”导入Head;
从“@apollo/react hooks”导入{apollo provider}”;
从“apollo客户端”导入{apollo客户端};
从“apollo缓存inmemory”导入{InMemoryCache};
从“阿波罗链接http”导入{HttpLink};
从“同构取消蚀刻”导入提取;
从“/create”导入CreateAppollClient;
让客户端=null;
/**
*创建并提供上下文
*转到下一个.js页面树。用包装的方式使用
*通过HOC模式创建页面组件。
*@param{Function | Class}PageComponent
*@param{Object}[config]
*@param{Boolean}[config.ssr=true]
*/
使用Apollo导出函数(PageComponent,{ssr=true}={}){
const with Apollo=({apolloClient,apolloState,…pageProps})=>{
const client=apolloClient | | initApolloClient(apolloState);
返回(

我有一个非常相似的体系结构,但使用的是Vue。通过比较您的代码和我的工作实现,我认为您的大多数问题都在create.js中

我对js cookie知之甚少,但这就是我获取XSRF-TOKEN并对其进行解码的方法

let token = RegExp('XSRF-TOKEN[^;]+').exec(document.cookie)
token = decodeURIComponent(token ? token.toString().replace(/^[^=]+./, '') : '')
然后,在setContext中,需要按如下方式设置头

return {
   headers: {
     ...headers,
     'X-XSRF-TOKEN': token,
   }
}
此外,即使我使用的是子域,我也无法使用凭据:“同源”。因此,我建议:

const httpLink = createHttpLink({
  uri: serverUrl,
  credentials: 'include',
})

我忘了删除这个问题。我昨晚修复了它。你的钱是对的。它在
create.js
文件中。我添加了
X-XSRF-TOKEN
,并更新了凭据以包含其值。谢谢你的回复。
'route' => [
        /*
         * The URI the endpoint responds to, e.g. mydomain.com/graphql.
         */
        'uri' => '/graphql',

        /*
         * Lighthouse creates a named route for convenient URL generation and redirects.
         */
        'name' => 'graphql',

        /*
         * Beware that middleware defined here runs before the GraphQL execution phase,
         * make sure to return spec-compliant responses in case an error is thrown.
         */
        'middleware' => [
            \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class,

            // Logs in a user if they are authenticated. In contrast to Laravel's 'auth'
            // middleware, this delegates auth and permission checks to the field level.
            \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class,
        ],

        /*
         * The `prefix` and `domain` configuration options are optional.
         */
        //'prefix' => '',
        //'domain' => '',
    ],
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import Cookies from 'js-cookie';
import { serverUrl } from '../config';

export default function createApolloClient(initialState, ctx) {
  // The `ctx` (NextPageContext) will only be present on the server.
  // use it to extract auth headers (ctx.req) or similar.

  const authLink = setContext((_, { headers  }) => {
    // get the authentication token from local storage if it exists
    const token = Cookies.get("XSRF-TOKEN");
    // console.log(`token is ${token}`);
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        "Access-Control-Allow-Credentials": true,
        ...(token ? { authorization: `X-XSRF-TOKEN=${token}` } : {}),
      },
    };
  });

  const httpLink = createHttpLink({
    uri: serverUrl,
    credentials: 'same-origin',
  });

  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: authLink.concat(httpLink),
    connectToDevTools: true,
    cache: new InMemoryCache().restore(initialState),
  });
}

import React from "react";
import Head from "next/head";
import { ApolloProvider } from "@apollo/react-hooks";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import fetch from "isomorphic-unfetch";
import createApolloClient from './create';

let apolloClient = null;

/**
 * Creates and provides the apolloContext
 * to a next.js PageTree. Use it by wrapping
 * your PageComponent via HOC pattern.
 * @param {Function|Class} PageComponent
 * @param {Object} [config]
 * @param {Boolean} [config.ssr=true]
 */
export function withApollo(PageComponent, { ssr = true } = {}) {
  const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
    const client = apolloClient || initApolloClient(apolloState);

    return (
      <ApolloProvider client={client}>
        <PageComponent {...pageProps} />
      </ApolloProvider>
    );
  };

  // Set the correct displayName in development
  if (process.env.NODE_ENV !== "production") {
    const displayName =
      PageComponent.displayName || PageComponent.name || "Component";

    if (displayName === "App") {
      console.warn("This withApollo HOC only works with PageComponents.");
    }

    WithApollo.displayName = `withApollo(${displayName})`;
  }

  if (ssr || PageComponent.getInitialProps) {
    WithApollo.getInitialProps = async (ctx) => {
      const { AppTree } = ctx;

      // Initialize ApolloClient, add it to the ctx object so
      // we can use it in `PageComponent.getInitialProp`.
      const apolloClient = (ctx.apolloClient = initApolloClient(
        {},
        ctx.req.headers.cookie
      ));

      // Run wrapped getInitialProps methods
      let pageProps = {};
      if (PageComponent.getInitialProps) {
        pageProps = await PageComponent.getInitialProps(ctx);
      }

      // Only on the server:
      if (typeof window === "undefined") {
        // When redirecting, the response is finished.
        // No point in continuing to render
        if (ctx.res && ctx.res.finished) {
          return pageProps;
        }

        // Only if ssr is enabled
        if (ssr) {
          try {
            // Run all GraphQL queries
            const { getDataFromTree } = await import("@apollo/react-ssr");
            await getDataFromTree(
              <AppTree
                pageProps={{
                  ...pageProps,
                  apolloClient,
                }}
              />
            );
          } catch (error) {
            // Prevent Apollo Client GraphQL errors from crashing SSR.
            // Handle them in components via the data.error prop:
            // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
            console.error("Error while running `getDataFromTree`", error);
          }

          // getDataFromTree does not call componentWillUnmount
          // head side effect therefore need to be cleared manually
          Head.rewind();
        }
      }

      // Extract query data from the Apollo store
      // @ts-ignore
      const apolloState = apolloClient.cache.extract();

      return {
        ...pageProps,
        apolloState,
      };
    };
  }

  return WithApollo;
}

/**
 * Always creates a new apollo client on the server
 * Creates or reuses apollo client in the browser.
 * @param  {Object} initialState
 */
function initApolloClient(initialState = {}, cookie = "") {
  // Make sure to create a new client for every server-side request so that data
  // isn"t shared between connections (which would be bad)

  if (typeof window === "undefined") {
    return createApolloClient(initialState, cookie);
  }

  // Reuse client on the client-side
  if (!apolloClient) {
    // @ts-ignore
    apolloClient = createApolloClient(initialState);
  }

  return apolloClient;
}

let token = RegExp('XSRF-TOKEN[^;]+').exec(document.cookie)
token = decodeURIComponent(token ? token.toString().replace(/^[^=]+./, '') : '')
return {
   headers: {
     ...headers,
     'X-XSRF-TOKEN': token,
   }
}
const httpLink = createHttpLink({
  uri: serverUrl,
  credentials: 'include',
})