Trouble getting an Authentication Token using Axios for React

1.6k views Asked by At

I'm trying to grab an authentication token using axios in a react app.

Here is the error I'm getting is: "XMLHttpRequest cannot load https://api.mmitnetwork.com/Token. Response for preflight has invalid HTTP status code 400"

Here is my code.

 var App = React.createClass({
  getInitialState() {
    return {
      token: ''
    }
  },
  componentDidMount() {
    var _this = this;

    axios.post('https://api.mmitnetwork.com/Token', {
      grant_type: 'password',
      username: 'jpdesigning',
      password: 'Upahem2_88'
    }).then((response) => {
      console.log('Success!')
      _this.setState({
        token: response.data
      })
    }).catch((error) => {
      console.log(error)
    })
   },
  render() {
    return (
      <div className="App">
           {this.state.token}
      </div>
     );
  }
})

export default App;
2

There are 2 answers

1
nazim On

Your server needs to allow cross-origin (CORS) clients to access your headers by setting the following header on your server's response and telling it which headers they are (here you are allowing two headers: Authorization & Permissions - i.e. including custom headers)

Access-Control-Expose-Headers: Authorization, Permissions

Headers that are accessible by default:

Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

Read here Access-Control-Expose-Headers

example from php server for full CORS access

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size,
X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
0
Sudeep C V On

you need to set withCredentials: true, header , this will send the cookie along with this request