I am trying to get POST requests to work coming from a React.js application to a Ruby on Rails API.
The parameters are:
Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}
My survey_params method is:
def survey_params
params.permit(:Name, :Draft_Status, :Active_Status)
end
My API Call from React is:
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' }`)
}
The following Curl Request allows me to enter new surveys without any issues:
curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey
How can I edit Rails or React to get the Post request to work properly in a way that allows the curl request to still work?
Update: Here is a picture from the logs: The first request is from Curl. The second request is from React. Hope this helps make the error more clear. Thanks for the help so far.
[
CodePudding user response:
Changed the POST body from a string to a JSON object. This caused Rails to accept the params.
post('survey',{Name: surveyDetails.name, Draft_Status: true, Active_Status: false})
Shoutout to max (https://stackoverflow.com/users/544825/max) for coming up with solution!
CodePudding user response:
In your controller you might want to skip forgery protection for json requests. It would be useful if you'd share a part of your logs where POST from React happens, otherwise it's hard to tell what the reason could be. This works when you get Can't verify CSRF token authenticity
for your POST requests.
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
end