Dhaval
Dhaval

Reputation: 29

fetch request not working with headers

I am working on login page with ReactJs,Spring Boot and rest web services.My Reactjs frontend application is running on port 8080 while my webservice/spring boot application is running on port 9090. I am trying to use the "fetch" method to connect with my backend code, but I am facing error while passing headers in fetch request. If I remove headers property, execution goes into the called backend method. I need to pass Headers in fetch method as it required to access them in web service method.

Please find Snapshot of network requests and responses. Without Headers With headers

Below is my code of React JSX file:

import React, { Component } from 'react';
class App extends Component {

    constructor(props){
        super(props);
        this.state={
            email:'',
            password:''
        }
        this.handleClick = this.handleClick.bind(this);
   }

    handleClick(){

       var usernameFieldValue = this.refs.emailField.value;
       var passwordFieldValue = this.refs.passwordField.value;
       this.setState({email:usernameFieldValue})
       this.setState({password:passwordFieldValue})

       //var headers = 'Basic bmltZXNoLnBhdGVsQHRhdHZhc29mdC5jb206cGFzc3dvcmQ=';
       //alert(headers);
        fetch('http://192.168.0.239:9090/ws/login',{
            mode: 'cors',
            method: 'get',
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Basic bmltZXNoLnBhdGVsQHRhdHZhc29mdC5jb206cGFzc3dvcmQ="    
            }
        }).then((response) => response.json())
        .then((responseJson) => {
           alert(" responseJson : " + responseJson);
          })
          .catch((error) => {
            alert("Error : " +error);
          });
    }    

    render() {
      return (
              <div id="loginFrame">
                  <div className="container">
                      <div id="loginHeader" className="row">
                          <div className="col-xs-12 text-center">
                              <img src="" alt="'Logo" />
                          </div>
                      </div>
                      <div id="loginBody" className="row">
                      <div className="col-xs-6 col-xs-offset-3">
                          <div className="center-block">
                              <div id="login-panel">
                                  <form id="loginForm" className="form-horizontal" role="form">
                                      <div className="form-group">
                                          <input type="text" className="form-control input-lg" id="email" name="email" ref="emailField" placeholder="Email address"/>
                                      </div>
                                      <div className="form-group">
                                          <input type="password" className="form-control input-lg" id="password" name="password" ref="passwordField" placeholder="Password"/>
                                      </div>
                                      <div className="form-group">
                                          <button onClick={this.handleClick} className="btn btn-lg btn-success pull-right">Login</button>
                                      </div>
                                  </form>
                              </div>
                          </div>
                        </div>
                      </div>
                  </div>
              </div>
      );
   }
}

export default App;

Upvotes: 2

Views: 8314

Answers (3)

Pankaj Bhardwaj
Pankaj Bhardwaj

Reputation: 2131

var url = "https://yourUrl";
    var bearer = 'Bearer '+ bearer_token;
    fetch(url, {
    method: 'GET',
    withCredentials: true,
    credentials: 'include',
    headers: {
        'Authorization': bearer,
        'X-FP-API-KEY': 'iphone',
        'Content-Type': 'application/json'}
    }).then((responseJson) => {
        var items = JSON.parse(responseJson._bodyInit);
    })
    .catch(error => this.setState({
    isLoading: false,
    message: 'Something bad happened ' + error
    }));

Upvotes: 1

ccnokes
ccnokes

Reputation: 7115

Based on your comments, it sounds like the underlying problem is that you're doing a CORS request from your react app, which is being served from a different server than your spring backend. I don't know Spring, but adding a Access-Control-Allow-Origin HTTP header (as well as some other CORS related headers) will clear up the problem. I'm not 100% sure why when you fetch with no headers, it works. There may be a deeper configuration issue or you need to configure it to allow requests with those headers you're passing (Access-Control-Allow-Headers). Note that if you don't plan to allow cross-origin requests in production you may want to add those headers except when in development.

You can also fetch in no CORS mode (pass {mode: 'no-cors'}), but there's a lot of limitations to that and I doubt that's what you want.

Upvotes: 0

Dan
Dan

Reputation: 8794

You don't need mode: cors, this is default.

const headers = new Headers({
  "Content-Type": "application/json",
  "Authorization": "Basic bmltZXNoLnBhdGVsQHRhdHZhc29mdC5jb206cGFzc3dvcmQ="  
});

fetch('http://192.168.0.239:9090/ws/login', {
  method: 'GET',
  headers,
}).then().then().catch();

Upvotes: 0

Related Questions