I have a React SPA with a Rails API. I recently changed my API requests on the React side to go through axios
instead of jquery and my axios
setup is:
export default class API {
static send(verb, resource, rawParams, callback, errcallback) {
const params = Object.keys(rawParams).reduce((o, k) => {
o[k] = rawParams[k];
return o;
}, {});
const errorCallback = typeof errcallback === 'function' ? errcallback : () => {};
const request = {
method: verb,
url: `${URL}/${resource}`
};
const token = window.sessionStorage.getItem('jwt');
request.headers = {};
if (token !== 'undefined' && token != null) {
request.headers.Authorization = `Bearer ${token}`;
}
if (verb === 'GET' || verb === 'DELETE') {
request.params = params;
request.headers['Content-Type'] = 'application/json';
request.headers.Accept = 'application/json';
} else {
request.headers['Content-Type'] = 'application/json';
request.headers.Accept = 'application/json';
request.data = params;
}
axios(request)
.then(response => {
if (resource === 'users/sign_in') {
const jwt = response.headers.authorization;
window.sessionStorage.setItem('jwt', jwt.split('Bearer ')[1]);
} else if (resource === 'users/sign_out') {
window.sessionStorage.removeItem('jwt');
}
callback(response.data);
})
.catch(error => {
errorCallback(error.response.data);
});
}
static baseURL() {
return URL;
}
static get(resource, params, callback, errcallback) {
API.send('GET', resource, params, callback, errcallback);
}
static post(resource, params, callback, errcallback) {
API.send('POST', resource, params, callback, errcallback);
}
static put(resource, params, callback, errcallback) {
API.send('PUT', resource, params, callback, errcallback);
}
static del(resource, params, callback, errcallback) {
API.send('DELETE', resource, params, callback, errcallback);
}
}
And to this I create a request such as:
API.get('user/user_auth', { validate_user: { user_type: 'gamer' } }. res => {
...
}
But now my Rails side fails in the permit param. The permit is defined as:
def user_type_params
params.require(:validate_user).permit(:user_type)
end
And every time I do something like user_type_params[:user_type]
in my Rails code I get an error such as:
NoMethodError (undefined method `permit' for "{\"user_type\":\"gamer\"}":String)`
It sends it as a string even though I added request.headers['Content-Type'] = 'application/json';
. Is there some other way to convert the params properly before making the request?
It turns out that Axios escaping nested JSON is a known issue: axios/issues/738.
The way to fix this was to add an interceptor in my api.js
such as:
axios.interceptors.request.use(config => {
config.paramsSerializer = params =>
qs.stringify(params, {
arrayFormat: 'brackets',
encode: false
});
return config;
});
This ensures that the nested params are converted properly before sending them to Rails