提问者:小点点

在React的第二个获取API中使用第一个获取的访问令牌JS


作为React的新手,我已经在如何让我的访问令牌在第二次获取API中使用上卡住了一段时间。在第一次获取(获取令牌)中,我能够成功地将我的访问令牌打印到控制台。我的问题是如何在第二次获取(获取数据)中使用此令牌作为承载授权。任何方向都受到赞赏。

2022年3月5日更新:我能够使用access_token键以JSON格式获取数据以登录到控制台。不过仍然无法在第二次获取中使用。

app. js(编辑了一些私人数据):

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      airData: []
    }
   }

componentDidMount(){

//Get token
var urlencoded = new URLSearchParams();
urlencoded.append("code", "MY_API_KEY");

var requestOptions = {
  method: 'POST',
  body: urlencoded,
  redirect: 'follow'
};

fetch("API_URL_FOR_TOKEN", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));



  //Get Data
  var myHeaders = new Headers();
      myHeaders.append("Authorization", "Bearer xxxxxxxxx");

      var urlencoded = new URLSearchParams();
      urlencoded.append("macAddress", "xxxxxxxxx");
      urlencoded.append("mode", "minute");

      var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
      };

  fetch("MAIN_API_URL", requestOptions)
   .then(response => response.json())
   .then(res => {
     console.log(res)
     this.setState({
       airData: res.data
     })
   });
  }


  
  render () {
        return (
          <div className="app">
             <header className="header">
                <div>
                <img src={logo} alt="Logo" className="logo" />
                    <div className="temperature">
                    
                        <FaTemperatureHigh /> 78°
                        
                    </div>
                </div>
            </header>
            <div className="spacer"></div>
            <OverallStatus />
            {this.state.airData.map(res => (
                  <div>
                    <div className='qualityFactor'>
                      <h1><img src={iconHumidity} alt="Logo" className="iconSmall" />Humidity <span className="right-justify">{res.humidity}%</span></h1>
                      <ProgressBar completed={res.humidity}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconAirPressure} alt="Logo" className="iconSmall" />Air Pressure <span className="right-justify">{res.airPressure} hPa</span></h1>
                      <ProgressBar completed={res.airPressure}
                      maxCompleted={1030} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonDioxide} alt="Logo" className="iconSmall" />Carbon Dioxide <span className="right-justify">{res.co2} ppm</span></h1>
                      <ProgressBar completed={res.co2}
                      maxCompleted={2000} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconVOCs} alt="Logo" className="iconSmall" />Chemicals <span className="right-justify">{res.tvoc} ppb</span></h1>
                      <ProgressBar completed={res.tvoc}
                      maxCompleted={1000} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconParticulateMatter} alt="Logo" className="iconSmall" />Particles <span className="right-justify">{res.pm25} ug/m3</span></h1>
                      <ProgressBar completed={res.pm25}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonMonoxide} alt="Logo" className="iconSmall" />Carbon Monoxide <span className="right-justify">{res.co} ppm</span></h1>
                      <ProgressBar completed={res.co}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconNitrogenDioxide} alt="Logo" className="iconSmall" />Nitrogen Dioxide <span className="right-justify">{res.no2} ppb</span></h1>
                      <ProgressBar completed={res.no2}
                      maxCompleted={200} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconOzone} alt="Logo" className="iconSmall" />Ozone <span className="right-justify">{res.ozone} ppb</span></h1>
                      <ProgressBar completed={res.ozone}
                      maxCompleted={100} className="statusBar" height="40px" baseBgColor="#8BC34A" isLabelVisible="true" customLabel="•" labelSize="240px" />
                    </div>
                  </div>
            ))}
          </div>
        )
    }
  }
  
  

export default App;


共1个答案

匿名用户

我对Reactjs太陌生了,如果我很了解你,我会这样管理:

我正在使用axios,但我认为步骤是相同的。

  1. 首先我在我的组件中声明一个状态变量(AxiosRequest estHeaders我添加了这个类型,因为我使用带有typescript的reactjs)
const [headers, setHeaders] = React.useState<AxiosRequestHeaders>({ 
        'Authorization':  ``,
        'My-Custom-Header': ''
       });
export const authenticate = async () => {  
    try {
        const response =  await axios.post(`${baseUrl}/authenticate`, { "username": "user", "password": "user"})     
         return { 
            'Authorization':  `Bearer ${response.data.id_token}`,
            'My-Custom-Header': 'foobar'
           };
           
    } catch(e) {
        console.log(e);
        return 0;
    }
}
import { authenticate } from './../api';
//..
useEffect(() => {
    (async () => {
      const userHeaders = await authenticate();
      setHeaders(userHeaders as AxiosRequestHeaders)
    })();
  }, []);

所以在这个useEffect中,我给了我的状态变量header ers它的值。因此,您可以在组件中的任何其他api方法中使用header ers变量。