Reactjs Axios / Spring boot security

2019-06-21 18:23发布

问题:

I have a Java application developed with Spring Boot which is the back-end. The front-end is an application developed in ReactJs. I use REST services. I use axios for REST calls. I recently enabled the security in Spring Boot. Now I have difficulty to authenticate axios calls.

var config = {
        auth: {
            username: 'bruker',
            password: 'passord'
        }

    };
    axios.get('http://localhost:8090/employee/all', config).then(function (response) {
        console.log(response)
    }.bind(this)).catch(function (response) {
        console.log(response)
    }.bind(this))

I get the following error "Response for preflight is invalid (redirect)" I assume the response is a redirected to localhost:8090/login I haven't found any solutions to this. What do I do wrong?

回答1:

This post is old now, but I ran into a similar problem here in good 'ole 2018. Using Axios as follows got things working for me:

    axios('/user', {
        method: 'POST',
        auth: {
            username: myUser,
            password: myPassword
        }
    }).then((response => {
        ...
    })).catch((error) => {
        ...
    })

Notice that the difference is replacing axios.get(... with axios(.... Remove the method type as a function and include it as a config option. It could have something to do with the way axios is imported (import axios from 'axios'), but I didn't delve into that once I got my stuff working.

Hope that helps!