3

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

sinaia
  • 31
  • 4
  • This might help you https://stackoverflow.com/questions/43842793/basic-authentication-with-fetch. – Aaron T Jul 21 '22 at 07:39
  • I tried all of that link content before I opened my own question. none of the answers solved my problem – sinaia Jul 21 '22 at 11:43
  • Solved : Couse of problem is web api cors configration. After web api cors enabled problem is solved. – sinaia Jul 22 '22 at 12:03

1 Answers1

2

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,
      })
  })

}
Ahmad Faraz
  • 1,371
  • 1
  • 4
  • 11
  • First of all, thank you for your interest. Gives 401 auth and syntax error on same line "fetch(url, {method:'GET', mode: 'no-cors', headers: {'Content-Type': 'application/json','Authorization': 'Basic ${base64encodedData}'}})" – sinaia Jul 20 '22 at 14:55
  • Sorry to bother you, I missed semi colon between `username` and `password`, are you using backTick on `Basic ${base64encodedData}` or strings? – Ahmad Faraz Jul 20 '22 at 18:48
  • I tried semicolon between username and password and bactick on Basic ${base64encodedData} result is the same. – sinaia Jul 21 '22 at 06:28
  • I used like this c# working succesfull. var client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"xxxxxx:Bxxxxxx"))); var response = await client.GetAsync("https://gd.xxxxxxxx.com.tr/api/Dates"); string newsJson = response.Content.ReadAsStringAsync().Result; – sinaia Jul 21 '22 at 06:39
  • I tried fetch(url, {headers: {'Authorization': 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64')}}) . This way I didn't get syntax error. Gave this error Access to fetch at 'https://gd.xxxxxxxx.com.tr/api/Dates' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. – sinaia Jul 21 '22 at 08:44
  • could you please try this. `fetch(url, {method:'GET', mode: 'no-cors', headers: {'Content-Type': 'application/json','Authorization': `Basic ${base64encodedData}`}})` – Ahmad Faraz Jul 21 '22 at 10:55
  • When I use no-cors it gives syntax error – sinaia Jul 21 '22 at 11:37
  • Couse of problem is web api cors configration. After web api cors enabled problem is solved. – sinaia Jul 22 '22 at 12:02
  • Have you tried adding a proxy line at the end of your package.json and then just fetch without the hostname, localhost or your server will proxy the request using the proxy host, and your cors issue should be solved. Don´t forget to change no-cors to cors in the request. – Curious Mind Nov 30 '22 at 20:00