Home > Software design >  How to call GET by axios has Bearer token?
How to call GET by axios has Bearer token?

Time:06-13

I am newbie in React and JavaScript development. I have file http-common.js

import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:8080/api",
    headers: {
        "Content-type": "application/json"
    }
});

File account.js

import React from 'react';
import 'devextreme/data/odata/store';

import axios from 'axios';

import DataGrid, {
    Column,
    Pager,
    Paging,
    FilterRow,
    Lookup
} from 'devextreme-react/data-grid';
import apiClient from "../../http-common";

export default function Accounts() {
    var bearer_token = "bearer "   localStorage.getItem("token");
    try {
        const config = {
            headers: {
                "Authorization": bearer_token
            },
        };
        // console.log(config);
        const res = apiClient.get("/account/all", config); // Please focus at this line, help me revise it for correct syntax/format of axios.

        axios.defaults.baseURL = 'http://localhost:8080/api'
        axios.defaults.headers.common = {'Authorization': bearer_token}
        var foo = axios.get("http://localhost:8080/api/account/all");
        console.log(foo)

        const result = {
            headers: res.headers,
            data: res.data,
        };
        console.log(res.data);

    } catch {
        return {
            isOk: false,
            message: "Đăng nhập thất bại"
        };
    }

    const dataSource = {
        store: {
            type: 'odata',
            key: 'Task_ID',
            url: 'https://js.devexpress.com/Demos/DevAV/odata/Tasks'
        },
        expand: 'ResponsibleEmployee',
        select: [
            'Task_ID',
            'Task_Subject',
            'Task_Start_Date',
            'Task_Due_Date',
            'Task_Status',
            'Task_Priority',
            'Task_Completion',
            'ResponsibleEmployee/Employee_Full_Name'
        ]
    };

    return (
        <React.Fragment>
            <h2 className={'content-block'}>Hệ thống tài khoản</h2>

            {/*<DataGrid*/}
            {/*    className={'dx-card wide-card'}*/}
            {/*    dataSource={dataSource}*/}
            {/*    showBorders={false}*/}
            {/*    focusedRowEnabled={true}*/}
            {/*    defaultFocusedRowIndex={0}*/}
            {/*    columnAutoWidth={true}*/}
            {/*    columnHidingEnabled={true}*/}
            {/*>*/}
            {/*    <Paging defaultPageSize={10}/>*/}
            {/*    <Pager showPageSizeSelector={true} showInfo={true}/>*/}
            {/*    <FilterRow visible={true}/>*/}

            {/*    <Column dataField={'Task_ID'} width={90} hidingPriority={2}/>*/}
            {/*    <Column*/}
            {/*        dataField={'Task_Subject'}*/}
            {/*        width={190}*/}
            {/*        caption={'Tài khoản'}*/}
            {/*        hidingPriority={8}*/}
            {/*    />*/}
            {/*    <Column*/}
            {/*        dataField={'Tên Tiếng Anh'}*/}
            {/*        caption={'Status'}*/}
            {/*        hidingPriority={6}*/}
            {/*    />*/}
            {/*    <Column*/}
            {/*        dataField={'Trạng thái theo dõi'}*/}
            {/*        caption={'Priority'}*/}
            {/*        hidingPriority={5}/>*/}

            {/*    <Column*/}
            {/*        dataField={'ResponsibleEmployee.Employee_Full_Name'}*/}
            {/*        caption={'Loại tài khoản'}*/}
            {/*        allowSorting={false}*/}
            {/*        hidingPriority={7}/>*/}

            {/*    <Column dataField={'Task_Start_Date'} caption={'Start Date'} dataType={'date'} hidingPriority={3}/>*/}

            {/*    <Column*/}
            {/*        dataField={'Task_Due_Date'}*/}
            {/*        caption={'Due Date'}*/}
            {/*        dataType={'date'}*/}
            {/*        hidingPriority={4}*/}
            {/*    />*/}
            {/*    <Column*/}
            {/*        dataField={'Task_Priority'}*/}
            {/*        caption={'Priority'}*/}
            {/*        name={'Priority'}*/}
            {/*        hidingPriority={1}*/}
            {/*    />*/}
            {/*    <Column*/}
            {/*        dataField={'Task_Completion'}*/}
            {/*        caption={'Completion'}*/}
            {/*        hidingPriority={0}*/}
            {/*    />*/}
            {/*</DataGrid>*/}
        </React.Fragment>
    )
}

This stuff works ok:

curl --location --request GET 'http://localhost:8080/api/account/all' \
--header 'Authorization: Bearer Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkb25odXZ5IiwiYXVkIjoiMSIsInNjb3BlcyI6W3siYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaXNzIjoic3lzdGVtIiwiaWF0IjoxNjU1MTIwMjA1LCJleHAiOjE2NTUxMzgyMDV9.YrHemJMFLFazc9uqknvG9KV_wzr26DBiVWc0r8I5xhU' \
--data-raw ''

enter image description here

enter image description here

enter image description here I try hard for a GET request, but not success. I don't know how to attach Bearer token to request. Please help me call GET request then return data.

CodePudding user response:

I see a difference in your provided code :
Your curl request start with Bearer Bearer while your JS one start with bearer .

I don't think you need 2 bearer but it probably require a capital letter

CodePudding user response:

Here is a documented example of how to do a "clean" component in your use case, I also put Bearer in capitalize so the call should work

import React from 'react';
import 'devextreme/data/odata/store';

import axios from 'axios';

import DataGrid, { Column, Pager, Paging, FilterRow, Lookup } from 'devextreme-react/data-grid';
import apiClient from '../../http-common';

export default function Accounts() {
  /* 
  ** state are special variable that are used to store data in react
  ** every time we change the state using the setSomething function, the component will re-render
  ** exemple: const [count, setCount] = useState(0);
  **         setCount(count   1); <== trigger a rerender of the component
  */
  const [dataSource, setDataSource] = React.useState([]); // <== here we use the useState to be able to show the data after we fetch it
  // on first render we will have no data, but when the data is fetched and stored in the state, it will trigger a rereder of the component


  /* 
  ** the callback inside the useEffect is called every time the dependencies array changes
  ** if you put an empty array [] as dependencies, the callback is called only once when the component is mounted
  ** if you put nothing as dependencies, the callback is called every time the component is updated
  ** if you put variables as dependencies, the callback is called every time one of those variables changes
  */ 
  React.useEffect(() => {
    async function getData() {
      const bearer_token = `Bearer ${localStorage.getItem('token')}`;
      try {
        const config = {
          headers: {
            Authorization: bearer_token
          }
        };
        const res = await apiClient.get('/account/all', config); // <== Here we use await keywords to get the result of the Promise, check internet if it's blurry for you
        setDataSource(res.data); // Maybe do some work on res.data to get the expected format
      } catch (err) {
        // here display a message to the user or something else
        console.error(err.message);
      }
    }

    getData(); // <== here we call the function to get the data
  }, []); // dependencies array is empty, so the callback is called only once when the component is mounted

  return (
    <React.Fragment>
      <h2 className={'content-block'}>Hệ thống tài khoản</h2>

      {/*<DataGrid*/}
      {/*    className={'dx-card wide-card'}*/}
      {/*    dataSource={dataSource}*/}
      {/*    showBorders={false}*/}
      {/*    focusedRowEnabled={true}*/}
      {/*    defaultFocusedRowIndex={0}*/}
      {/*    columnAutoWidth={true}*/}
      {/*    columnHidingEnabled={true}*/}
      {/*>*/}
      {/*    <Paging defaultPageSize={10}/>*/}
      {/*    <Pager showPageSizeSelector={true} showInfo={true}/>*/}
      {/*    <FilterRow visible={true}/>*/}

      {/*    <Column dataField={'Task_ID'} width={90} hidingPriority={2}/>*/}
      {/*    <Column*/}
      {/*        dataField={'Task_Subject'}*/}
      {/*        width={190}*/}
      {/*        caption={'Tài khoản'}*/}
      {/*        hidingPriority={8}*/}
      {/*    />*/}
      {/*    <Column*/}
      {/*        dataField={'Tên Tiếng Anh'}*/}
      {/*        caption={'Status'}*/}
      {/*        hidingPriority={6}*/}
      {/*    />*/}
      {/*    <Column*/}
      {/*        dataField={'Trạng thái theo dõi'}*/}
      {/*        caption={'Priority'}*/}
      {/*        hidingPriority={5}/>*/}

      {/*    <Column*/}
      {/*        dataField={'ResponsibleEmployee.Employee_Full_Name'}*/}
      {/*        caption={'Loại tài khoản'}*/}
      {/*        allowSorting={false}*/}
      {/*        hidingPriority={7}/>*/}

      {/*    <Column dataField={'Task_Start_Date'} caption={'Start Date'} dataType={'date'} hidingPriority={3}/>*/}

      {/*    <Column*/}
      {/*        dataField={'Task_Due_Date'}*/}
      {/*        caption={'Due Date'}*/}
      {/*        dataType={'date'}*/}
      {/*        hidingPriority={4}*/}
      {/*    />*/}
      {/*    <Column*/}
      {/*        dataField={'Task_Priority'}*/}
      {/*        caption={'Priority'}*/}
      {/*        name={'Priority'}*/}
      {/*        hidingPriority={1}*/}
      {/*    />*/}
      {/*    <Column*/}
      {/*        dataField={'Task_Completion'}*/}
      {/*        caption={'Completion'}*/}
      {/*        hidingPriority={0}*/}
      {/*    />*/}
      {/*</DataGrid>*/}
    </React.Fragment>
  );
}
  • Related