I am following this video tutorial from Rem Zolotykh. I am having the problem that querying the LoopBack server within an onSubmit() from a Form works and using a Redux Action with the same query gives me a Cross-Origin error.
LoopBack Server running at localhost:3000
React Webpack Server running at localhost:3001 (I used create-react-app)
This following onSubmit function works. Please don't mind the hardcoded stuff it is just for testing.
--------------SignupForm.js-----------------
...
onSubmit(e) {
const user_data = { "email": "foo@bar.com",
"password": "xxx" };
axios.post('http://localhost:3000/api/Users/login', user_data)
.then((response) => {
auth_token = { headers: { 'Authorization': response.data.id } };
return axios.get('http://localhost:3000/api/empsecure', auth_token)
})
.then((response) => {
console.log('Queried Data:', response);
return axios.post('http://localhost:3000/api/Users/logout',{},auth_token)
})
.then((response) => {
console.log("logged out", response);
});
}
...
Here is the changed onSubmit() and the Redux Action:
--------------SignupForm.js-----------------
...
onSubmit(e) {
this.props.userSignupRequest(this.state);
}
...
-------------signupActions.js---------------
import axios from 'axios';
export function userSignupRequest(userData) {
return dispatch => {
const auth_token = {
headers: {'Authorization': 'BgKeyYGVWxx5ybl649jhiPiHpZAyACmV6d9hfJ5UAJxs1McR4RaqANBgwP8vEqiH'}
};
axios.get('http://localhost:3000/api/empsecure', auth_token)
.then((response) => {
console.log('Queried Data:', response);
return response
});
}
}
The browser console gives me a Cross-Origin error, I understand that. But why does it work without redux then?
Ok, after researching, surfing internet and lot of code changes,
I found its required in this case to prevent the default action for onSubmit().
I think it did not like the page reload.
Works now.
onSubmit(e) {
e.preventDefault();
this.props.userSignupRequest(this.state);
}