【问题标题】:Strong parameters with JSON request带有 JSON 请求的强参数
【发布时间】: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 执行请求,选择POSTraw body 类型为application/json。它应该可以工作。
  • 请显示向 Rails 后端发出请求的代码。
  • 你试过解析 JSON 吗? JSON.parse(params) 这将给出正确的 json 格式,而不是字符串
  • 更新了发出请求的代码。
  • 根据文档,将params: 替换为data:。有区别吗?

标签: ruby-on-rails json ruby-on-rails-5 strong-parameters


【解决方案1】:

根据文档here

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

params: 替换为data:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2014-02-15
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多