【发布时间】:2017-05-03 12:56:29
【问题描述】:
我认为如果请求被识别为 JSON,Rails 会自动识别/解析 JSON 参数。但是下面的请求:
Processing by Api::V1::LinksController#create as JSON
Parameters: {"link"=>"{\"title\":\"My first title\"}"}
还有以下params方法:
def link_params
params.require(:link).permit(:title)
end
导致此错误:
NoMethodError(未定义方法 `permit' for "{\"title\":\"My first title\"}":String):
任何想法这里的约定是什么让强大的参数 + json 工作将不胜感激。
更新
这是发出请求的代码(使用 http 客户端 axios):
axios({
method: 'post',
url: '/api/v1/links.json',
responseType: 'json',
params: {
link: {
title: "My first title"
}
},
})
.then( (response) => {
});
【问题讨论】:
-
这似乎不是 json 正文,而是字符串。尝试使用
postman执行请求,选择POST和raw body类型为application/json。它应该可以工作。 -
请显示向 Rails 后端发出请求的代码。
-
你试过解析 JSON 吗? JSON.parse(params) 这将给出正确的 json 格式,而不是字符串
-
更新了发出请求的代码。
-
根据文档,将
params:替换为data:。有区别吗?
标签: ruby-on-rails json ruby-on-rails-5 strong-parameters