Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request with Basic authorization for React js app

Tags:

reactjs

I try to do a get request with basic authentication using React JS. I try to do it as follows:

    import React,{Component} from 'react';
    import { encode } from "base-64";
     
    export class MyDates extends Component{
    constructor(props){
        super(props);
        this.state = {
            items:[],
            isLoaded:false,
        }
    }
    
    componentDidMount(){
        let url = 'https://gd.xxxxxx.com.tr/api/Dates';
        let username = 'xxxxxxx';
        let password = 'Bxxxxxxxxx';
     
    
       fetch(url, {method:'GET', mode: 'no-cors', headers: {'Content-Type': 'application/json','Authorization': 'Basic ' + encode('${username}:${password}')}})
        .then(res=>res.json())
        .then(json => {
            this.setState({
                isLoaded:true,
                items:json,
            })
        })
    
    }
    
        render(){
            var  {isLoaded,items} = this.state;
            if(!isLoaded){
                return<div>Loading...</div>;
            }
            else
            {
                return(
                    <div className='container'>
                        <h3>Randevularım sayfası</h3>
                        <div className='row'>
                           {items.map(item => (
                            //item.completed == true ?
                               <div className='col-md-4 px-4 py-2' key={item.MAHALLEID}>
                                   <div className='m-2 rounded' style={{background:'#e2e2e2'}} >{item.MAHALLE}</div>
                               </div>
                               //:null
                           ))};
                        </div>
                    </div>
                )
            }
        }
    }

Api, user and password checked.

I get the following error:

Failed to load resource: the server responded with a status of 401 () MyDates.js:19 Uncaught (in promise) SyntaxError: Unexpected end of input (at MyDates.js:19:1) at MyDates.js:19:1

enter image description here

like image 447
sinaia Avatar asked Oct 23 '25 15:10

sinaia


1 Answers

could you please try this. I hope this works.

componentDidMount(){
  let url = 'https://gd.xxxxxx.com.tr/api/Dates';
  let username = 'xxxxxxx';
  let password = 'Bxxxxxxxxx';
  const base64encodedData = Buffer.from(`${username}:${password}`).toString('base64');

 fetch(url, {method:'GET', mode: 'no-cors', headers: {'Content-Type': 'application/json','Authorization': `Basic ${base64encodedData}`}})
  .then(res=>res.json())
  .then(json => {
      this.setState({
          isLoaded:true,
          items:json,
      })
  })

}
like image 190
Ahmad Avatar answered Oct 26 '25 04:10

Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!