Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

reactjs - How to pass auth token that I can access API?(react question)

I am making a simple app for lending phones with this api but I am unable to access the phone items as the request requires auth token. So I am trying to output this

import React from 'react'
import { MobileContext } from './MobileContext';
import { useContext } from 'react';
import Mobile from './Mobile';
import Navbar from './Navbar';
function MobileList() {
    const { mobiles } = useContext(MobileContext);
    return (
        <div>
            <Navbar/>
         {mobiles.map((item) => (
          <Mobile
           vendor={item.vendor} 
           
          />
        ))}  
        
       
        </div>
    )
}

export default MobileList

but after correct login getting this without the phones this

this is how my context api is set up but apparently I am unable to access the phones

import React, { useState, useEffect, createContext
 
} from 'react';
import axios from 'axios';


export const MobileContext = createContext({
 mobiles: [],
  setMobiles: () => {},
  updateMobiles: () => {},
});

export default function MobileProvider(props) {
  const [mobiles, setMobiles] = useState([]);
  
  

  
  const updateMobiles = (id) => {
 
    axios
      .get('https://js-test-api.etnetera.cz/api/v1/phones')
      .then((res) => setMobiles(res.data));
  };

  useEffect(() => {
    axios
      .get('https://js-test-api.etnetera.cz/api/v1/phones')
      .then((res) => setMobiles(res.data));
      
  }, [] );

  return (
    <MobileContext.Provider value={{ mobiles, setMobiles, updateMobiles}}>
      {props.children}
    </MobileContext.Provider>
  );
}

then there is the login page you have to get through if you want to get to the phones page

import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import { useHistory } from "react-router-dom";
function Login() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    
   
    let history = useHistory()
    const onSubmit = (e) => {
      e.preventDefault();
      const getIn = {
      
        "login":email,
        "password":password,
        
    
      };
  
      
      axios
        .post('https://js-test-api.etnetera.cz/api/v1/login', getIn,
        {
            headers: {
                
                 'content-type': 'application/json', 
           }
        }).then((res) => {
      console.log(res.data); 
      history.push("/phones");
    })
        .catch((error) => console.log(error));
       
    };
    return (
        <div>
           <form >
         <label>email</label> <input value={email}
          onChange={(e) => setEmail(e.target.value)} type="text"/>
        <label>password</label>  <input type="text" value={password}
          onChange={(e) => setPassword(e.target.value)}/>
        <button onClick={onSubmit}>login</button>
           </form>
        </div>
    )
}

export default Login

apreciate any advice of how to pass the auth tokens as I have never done this here is the full code

question from:https://stackoverflow.com/questions/65892016/how-to-pass-auth-token-that-i-can-access-apireact-question

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The idea of tokens is that once a user successfully logs in (the POST request), he receives a token from the server (the login's response).

Once a user has his token (stored preferably in a browser's localStorage, to keep it regardless the browser's refresh), he passes this token along with every request to the server that needs authentication.

I.e., for JWT tokens that header is:

Authorization: Bearer [token]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...