【问题标题】:How to pass auth token to endpoint?如何将身份验证令牌传递给端点?
【发布时间】:2021-04-13 11:27:30
【问题描述】:

我是令牌授权的初学者,我正在尝试使用 react 创建登录系统。端点似乎需要访问令牌,所以我被重定向到 /home,这目前没有发生。我正在使用这个 api https://app.swaggerhub.com/apis/warp/etn-device-checker-test/1.0#/default/post_login

登录.js

import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import { Redirect } from "react-router-dom";
function Login() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    
   
  
    const onSubmit = (e) => {
      e.preventDefault();
      const getIn = {
      
        "login":email,
        "password":password,
        
    
      };
  
      axios
        .post('https://js-test-api.etnetera.cz/api/v1/login', getIn,
        {
            headers: {
                authorization: 'Auth-Token',
                 'content-type': 'application/json', 
           }
        })
        .then((res) => {
          console.log(res.data); 
          return <Redirect to="/home" />
         
        })
        .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

App.js

import './App.css';
import Login from './Login';
import MobileList from './mobileList';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function App() {
  return (
    <div className="App">
 <Router>
 <Switch>
 
<Route>
<Login path='/' exact/>
</Route>
<Route>
 <MobileList path='/home' />
 </Route>
</Switch>
 </Router>
 
    </div>
  );
}

export default App;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    headers: {"Authorization" : `Bearer ${token}`}

    也许这个答案会对你有所帮助。 how-to-pass-header-jwt-token-with-axios-react

    但在登录时,我认为您不需要令牌, 所以你可以在那里删除授权部分。

    【讨论】:

      猜你喜欢
      • 2019-06-16
      • 1970-01-01
      • 2015-02-24
      • 2011-08-16
      • 2016-10-01
      • 2020-06-29
      • 2021-08-17
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多