I read and found that axios will make the call for json format to an endpoint, which doesn't seem to be the case here. My endpoint looks like this:
def create
@form = Form.new(form_params)
if @form.save
respond_to do |format|
format.html { redirect_to(@form, notice: "Form created successfully") }
format.json { render json: {message: "Form created successfully"} }
end
else
respond_to do |format|
format.html { render 'new' }
format.json { render json: {errors: @form.errors}, status: :unprocessable_entity }
end
end
end
My axios call looks like this:
function instance() {
return axios.create({
headers: {'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')},
'Content-Type': 'application/json',
responseType: 'json'
});
}
function post(url, data={}) {
return instance().post(url, data)
}
here is how I make the call:
post('/forms', {
form: this.$data
}).then((response) => {
console.log("success");
console.log(response.data);
}).catch((error) => {
console.log("errro");
console.log(error.response);
})
}
It works if change /forms
to /forms.json
, any tip on how to fix this?
The correct header key should be Accept. So in reference to your question it should work with: axios.create({headers: {'Accept': 'application/json'}})
Apart of that, it is worth considering to set axios's default headers in a suitable location, like this:
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
axios.defaults.headers.common['X-CSRF-Token'] = token
axios.defaults.headers.common['Accept'] = 'application/json'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With