You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React环境变量失效求助:REACT_APP_GET_CLIENT_URL无法正常使用

Fixing React Environment Variable Issue with Dynamic Values

Hey there, let's break down why your REACT_APP_GET_CLIENT_URL isn't working, while REACT_APP_LOGIN_URL works just fine.

The Root Problem

React environment variables are static values injected at build time—they can't recognize runtime dynamic variables like ${res.data.userId} or ${res.data.id} that exist only in your code after the login API call. When you define REACT_APP_GET_CLIENT_URL with those template literals in your .env file, it's treated as a literal string, not a dynamic template that gets evaluated later in your code. That's why the request fails—it's trying to hit a URL with ${res.data.userId} in the path instead of the actual user ID from your login response.

The Fix

You need to split the static base URL into an environment variable, then dynamically append the user ID and access token in your code when making the request. Here's how to do it:

  1. Update your .env file
    Change the variable to just the static base part of the URL:

    REACT_APP_GET_CLIENT_BASE_URL=http://localhost:3002/api/clients
    
  2. Modify your code to build the dynamic URL
    In your login function, after getting the login response, construct the full URL by combining the base environment variable with the dynamic values. You have two clean options:

    Option 1: Template Literal (simple approach)

    login: (data) => {
      axios.post(process.env.REACT_APP_LOGIN_URL, data)
        .then((res) => {
          localStorage.setItem('token', res.data.id)
          localStorage.setItem('userId', res.data.userId)
          // Build the dynamic URL here
          const clientUrl = `${process.env.REACT_APP_GET_CLIENT_BASE_URL}/${res.data.userId}?access_token=${res.data.id}`
          axios.get(clientUrl)
            .then((res) => {
              localStorage.setItem('firstName', res.data.firstName)
              localStorage.setItem('lastName', res.data.lastName)
              localStorage.setItem('picture', res.data.picture)
              localStorage.setItem('namePicture', res.data.namePicture)
              dispatch({type: 'LOGIN'});
            })
        })
        .catch((err) => {
          console.log(err);
          dispatch({type: 'LOGIN_ERR'});
        })
    }
    

    Option 2: Using URL and URLSearchParams (more robust for query parameters)

    This is better if you might add more query parameters later, as it handles encoding automatically:

    login: (data) => {
      axios.post(process.env.REACT_APP_LOGIN_URL, data)
        .then((res) => {
          localStorage.setItem('token', res.data.id)
          localStorage.setItem('userId', res.data.userId)
          // Build URL with proper parameter handling
          const baseUrl = process.env.REACT_APP_GET_CLIENT_BASE_URL;
          const clientUrl = new URL(`${baseUrl}/${res.data.userId}`);
          clientUrl.searchParams.append('access_token', res.data.id);
          
          axios.get(clientUrl.toString())
            .then((res) => {
              localStorage.setItem('firstName', res.data.firstName)
              localStorage.setItem('lastName', res.data.lastName)
              localStorage.setItem('picture', res.data.picture)
              localStorage.setItem('namePicture', res.data.namePicture)
              dispatch({type: 'LOGIN'});
            })
        })
        .catch((err) => {
          console.log(err);
          dispatch({type: 'LOGIN_ERR'});
        })
    }
    

Quick Reminders

  • Always restart your React development server after modifying .env files—new or updated variables won't take effect until you do.
  • All custom environment variables in React must start with REACT_APP_ (you're already doing this correctly, just a quick check!).
  • Environment variables are meant for static configuration (like base URLs, API keys, etc.)—dynamic values that depend on runtime data should always be handled in your code.

内容的提问来源于stack exchange,提问作者TROGER Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:21:26