[英]Ruby on Rails: How to Permit parameters with "_json"
我正在嘗試使來自 React.js 應用程序的 POST 請求工作到 Rails API 上的 Ruby。
參數是:
Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}
我的 survey_params 方法是:
def survey_params
params.permit(:Name, :Draft_Status, :Active_Status)
end
我的 API 來自 React 的電話是:
const post = (endpoint, body) => {
const url = ANAMNESIS_CONFIG.backend.location + endpoint ?? '';
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Anamnesis-Secret': ANAMNESIS_CONFIG.backend.secret
},
body: JSON.stringify(body)
}).then(response => response.json())
};
const submitHandler = e => {
e.preventDefault();
console.log({ surveyDetails })
post('survey',`{'Name': '${surveyDetails.name}', 'Draft_Status': 'true', 'Active_Status': 'false' }`)
}
以下 Curl 請求允許我毫無問題地輸入新的調查:
curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey
我如何編輯 Rails 或 React 以使 Post 請求以允許 curl 請求仍然有效的方式正常工作?
更新:這是日志中的圖片:第一個請求來自 Curl。第二個請求來自 React。 希望這有助於使錯誤更清楚。 感謝你目前的幫助。
[
將 POST 正文從字符串更改為 JSON object。這導致 Rails 接受參數。
post('survey',{Name: surveyDetails.name, Draft_Status: true, Active_Status: false})
向 max ( https://stackoverflow.com/users/544825/max ) 提出解決方案大喊大叫!
在您的 controller 中,您可能希望跳過 json 請求的偽造保護。 如果您在 React 的 POST 發生的地方共享您的日志的一部分,這將很有用,否則很難說出原因是什么。 當您收到Can't verify CSRF token authenticity
for your POST requests 時,這會起作用。
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.