N
N
Nina2022-04-12 17:59:39
React
Nina, 2022-04-12 17:59:39

How to fix the You are not authorized error?

With the help of GraphQL, I made a registration and a separate login Login. There are no errors during registration. At the entrance, if I write the wrong email, the server shows that there is no such email. If I write the correct email, then everything is fine. But when you try to enter the application on a page where information from the server should be displayed, the server gives the error You are not authorized. What did I write wrong? Please write the code, otherwise I don’t understand GraphQL and have been looking for information on the Internet all day, but I can’t find it. My code is
index.js:

import ReactDOM from "react-dom";
import App from "./components/App/App";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider  
} from "@apollo/client";i
import { Provider } from "react-redux";

const client = new ApolloClient( {
  uri: "http://localhost:4000/api",
  cache: new InMemoryCache() 
} );


ReactDOM.render(
  <React.StrictMode>  
      <ApolloProvider client={ client }>
        <App/>
      </ApolloProvider>
  </React.StrictMode>,
  document.getElementById( "root" )
);


Login.js:
import { gql, useMutation, useQuery } from "@apollo/client";

const LOG_IN = gql`
  mutation LogIn($email: String! 
                 $password: String!) {
    login ( email: $email, password: $password ) {
      token
    }
  }
`;

function LogIn() {
 const navigate = useNavigate();
const [ login, { error }, ] = useMutation( LOG_IN, {
    onCompleted: ({ login }) => {
      localStorage.setItem( AUTH_TOKEN, login.token );
      dispatch( logIn() );
      navigate( "/process" );
    }
  } );

const onSubmit = async({ email, password }) => {
    console.log( email, password );
    login( {
      variables: {
        email: email,
        password: password
      }
    } );   
  };

<form>......


Process.js (which should receive data from the server):
const GET_PROCESS = gql`
  query GetProcess {
    processList {
      id
      name
    }
  }
`;

function Process() { 
  const { loading, error, data } = useQuery( GET_PROCESS );

  console.log(data);

  if( loading ) return "Loading...";
  if( error ) return `Error! ${ error.message }`;

  return (
    <>
      <h1>Process</h1>
        ...
    </>
  );
}

export default Process;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2022-04-12
@EugeneLobach

It is necessary that the server understands which user the request came from.
That is, you need to pass in the request header the token that you most likely receive from the server when you login.
But how to transfer it already depends on the server itself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question