4

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

3
  • This might help you stackoverflow.com/questions/43842793/…. Commented Jul 21, 2022 at 7:39
  • I tried all of that link content before I opened my own question. none of the answers solved my problem Commented Jul 21, 2022 at 11:43
  • Solved : Couse of problem is web api cors configration. After web api cors enabled problem is solved. Commented Jul 22, 2022 at 12:03

1 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

9 Comments

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}'}})"
Sorry to bother you, I missed semi colon between username and password, are you using backTick on Basic ${base64encodedData} or strings?
I tried semicolon between username and password and bactick on Basic ${base64encodedData} result is the same.
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("gd.xxxxxxxx.com.tr/api/Dates"); string newsJson = response.Content.ReadAsStringAsync().Result;
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 'gd.xxxxxxxx.com.tr/api/Dates' from origin '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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.