如何POST JSON 属性带下划线?
How to POST JSON attributes with underscore?
问题:
在服务器上,我收到我的 api_key
参数作为 api key
( 使用 space 而不是下划线 ),我如何发送它 带下划线?
代码:
data = {
api_key: this.state.api_key
}
axios.post('/resource', data)
.then(response => { console.log(response) });
我同时使用 React 和 axios(必须 使用 axios)前端,Rails 在后端。
谢谢
更新
第一个接收参数的rails动作:
private
resource_params
ActiveModelSerializers::Deserialization.jsonapi_parse(params)
end
Axios serializes object params with JSON.stringify
, which means the request is almost certainly being sent how you want (unless you are transforming it somehow). The issue is probably something on the Rails end. Looking at your resource_params
method, I can see you are using ActiveModelSerializers's JSON API adapter. However, the request you are sending with Axios is not JSON API Compliant. You might try JSON.parse(params)
instead or better yet, use Strong Params。您还提到您正在使用 resource_params
作为之前的操作,但看起来您并不像人们预期的那样在那里分配实例变量。您如何处理该响应?您是否也在您的操作中直接调用该方法?
无论如何,如果这没有帮助,我很乐意在聊天中继续我们的讨论。
经过几个小时的思考,我找到了罪魁祸首:Visual Studio代码
这是 VS Code 上的输出:
这是 linux 终端上的输出:
这是一个非常愚蠢的问题,但我从没想过该死的文本编辑器会省略下划线。
真的 @chris-g,这不是 JSON 或 React 的问题,它在 Rails 方面,因为 @Xavier 怀疑,尽管这个问题与缺少下划线本身无关。
这就是我在这么久之后给予微软一些信任的结果。
问题:
在服务器上,我收到我的 api_key
参数作为 api key
( 使用 space 而不是下划线 ),我如何发送它 带下划线?
代码:
data = {
api_key: this.state.api_key
}
axios.post('/resource', data)
.then(response => { console.log(response) });
我同时使用 React 和 axios(必须 使用 axios)前端,Rails 在后端。
谢谢
更新
第一个接收参数的rails动作:
private
resource_params
ActiveModelSerializers::Deserialization.jsonapi_parse(params)
end
Axios serializes object params with JSON.stringify
, which means the request is almost certainly being sent how you want (unless you are transforming it somehow). The issue is probably something on the Rails end. Looking at your resource_params
method, I can see you are using ActiveModelSerializers's JSON API adapter. However, the request you are sending with Axios is not JSON API Compliant. You might try JSON.parse(params)
instead or better yet, use Strong Params。您还提到您正在使用 resource_params
作为之前的操作,但看起来您并不像人们预期的那样在那里分配实例变量。您如何处理该响应?您是否也在您的操作中直接调用该方法?
无论如何,如果这没有帮助,我很乐意在聊天中继续我们的讨论。
经过几个小时的思考,我找到了罪魁祸首:Visual Studio代码
这是 VS Code 上的输出:
这是 linux 终端上的输出:
这是一个非常愚蠢的问题,但我从没想过该死的文本编辑器会省略下划线。
真的 @chris-g,这不是 JSON 或 React 的问题,它在 Rails 方面,因为 @Xavier 怀疑,尽管这个问题与缺少下划线本身无关。
这就是我在这么久之后给予微软一些信任的结果。