简体   繁体   中英

How do I send a variable from Express.js backend to React.js frontend?

I am trying to send my variable 'backEndResponse' with its value from my Express.js backend to my React.js Frontend. I am not quite sure how to send a variable from the backend to the frontend. I have searched around and can't find any good resources. I would appreciate any help.

Express.js Backend

function getcookie(req) {
    var authCookie = req.headers.cookie;
    if (authCookie = req.headers.cookie) {
        try {
            return authCookie
                .split('; ')
                .find(row => row.startsWith('Auth='))
                .split('=')[1];
        } finally {
            if (authCookie = result) {
                backEndResponse = true
                console.log(backEndResponse);
                console.log(result);
            } else {
                backEndResponse = false
                console.log(backEndResponse);
                console.log(result);
            }

        }
    } else {

    }
}

app.get('/auth', (req, res) => {
    getcookie(req)

    if (backEndResponse) {
        res.json(backEndResponse); // OR json({ message: "Authorised" })
      } else {
        res.json(backEndResponse); // OR json({ message: "Unauthorised" })
    }
});

Frontend React.js

    const useAuth = () => {
    const [data, setData] = useState();

      useEffect(() => {
          const fetchAuthData = () => {
            const result = axios('http://localhost:5000/auth');

            console.log(result)
            setData(result.data);
            
          };

          fetchAuthData()
      }, []);

      
    // Logic to check if backEndResponse is true or false
    if (data) {
        const authorized = {loggedIn: true}
        return authorized && authorized.loggedIn;
    } else {
        const authorized = {loggedIn: false}
        return authorized && authorized.loggedIn;
    }
  }


const ProtectedRoutes = () => {
    const isAuth = useAuth();
    return isAuth ? <Outlet/> : <Navigate to="/login" />;
}

You won't be able to send a variable directly, rather you will send a payload in a certain shape that best represents the data suited to the applications needs. To send a response payload in an express route use something like the following:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...
  res.json(backEndResponse);
});

If you were intending to provide more information in the response such as HTTP headers differing based on the of backEndResponse then you might consider:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...

  // send HTTP Ok if true, otherwise Bad Request
  // consider handling 400 and/or 500 errors too
  if (backEndResponse) {
    res.status(200).json(true); // OR json({ message: "Authorised" })
  } else {
    res.status(401).json(false); // OR json({ message: "Unauthorised" })
  }
});

A component fetching the above endpoint would be similar to:

const MyComponent = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchAuthData = async () => {
      const result = await axios('http://localhost:5000/auth');

      setData(result.data); // true/false OR { message: "Authorised" }
    };

    fetchAuthData();
  }, []);

  // display payload
  return (<div>{JSON.stringify(data)}</div>)
}

There is an opportunity to refactor the above into a custom hook should you find the need to reuse the functionality across multiple components.

axios request is async function, so you should do like that,

const useAuth = async () => {
  try {
    const res = await axios.get('http://localhost:5000/auth', {
      withCredentials: true
    })
    return true
  } catch (e) {
    return false
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM