gpt4 book ai didi

ruby-on-rails - NoMethodError:未定义字符串的方法 'permit'

转载 作者:行者123 更新时间:2023-12-05 07:26:15 25 4
gpt4 key购买 nike

我有一个带有 Rails API 的 React SPA。我最近更改了 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 端在 permit 参数中失败了。许可证定义为:

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';,它仍将其作为字符串发送。在发出请求之前是否有其他方法可以正确转换参数?

最佳答案

尝试这样的事情:

def user_type_params
json = params.require(:validate_user)
{user_type: JSON.parse(json).permit(:user_type)}
end

此外,您不一定需要使用许可。您可以自己将参数列入白名单。

关于ruby-on-rails - NoMethodError:未定义字符串的方法 'permit',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54488114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com