我有一个带Rails API的React Spa。我最近在React端更改了我的API请求以通过
axios
而不是jquery和my
阿西奥斯
设置是:
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);
}
}
为此,我创建了一个请求,例如:
API.get('user/user_auth', { validate_user: { user_type: 'gamer' } }. res => {
...
}
但是现在我的Rails侧在permit参数中失败了。许可证定义如下:
def user_type_params
params.require(:validate_user).permit(:user_type)
end
每次我做类似的事情
user_type_params[:user_type]
在我的Rails代码中,我得到一个错误,例如:
NoMethodError (undefined method `permit' for "{\"user_type\":\"gamer\"}":String)`
它以字符串形式发送,即使我添加了
request.headers['Content-Type'] = 'application/json';
. 在发出请求之前,是否有其他方法可以正确转换参数?