我有一个React SPA和一个Rails API。最近,我在React方面将API请求更改为通过axios
而不是jquery进行,我的axios
设置如下:
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端在允许参数方面失败了。 允许参数定义为:
def user_type_params
params.require(:validate_user).permit(:user_type)
end
每次在我的Rails代码中执行user_type_params[:user_type]
这样的操作,都会出现如下错误:
NoMethodError (undefined method `permit' for "{\"user_type\":\"gamer\"}":String)`
即使我添加了request.headers ['Content-Type'] ='application / json';
,它仍然将其作为字符串发送。在发出请求之前是否有其他方法可以正确转换参数?
{ user_type: 'gamer' }
作为有效载荷。我相信您没有遵循Rails控制器的约定。您应该发布控制器的片段。例如,如果您有用户控制器,则应执行params.require(:user).permit(:user_type)
,然后在客户端中,支付应仅为{user_type:“gamer”}
。 - tkhuynh