aks*_*aks 7 json ruby-on-rails axios
我阅读并发现 axios 会将 json 格式的调用发送到端点,这里似乎并非如此。我的端点如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我的 axios 调用如下所示:
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)
}
Run Code Online (Sandbox Code Playgroud)
这是我拨打电话的方式:
post('/forms', {
form: this.$data
}).then((response) => {
console.log("success");
console.log(response.data);
}).catch((error) => {
console.log("errro");
console.log(error.response);
})
}
Run Code Online (Sandbox Code Playgroud)
如果更改/forms为/forms.json,它会起作用,有关如何解决此问题的任何提示?
正确的标题键应该是接受。因此,关于您的问题,它应该适用于:axios.create({headers: {'Accept': 'application/json'}})
除此之外,值得考虑在合适的位置设置 axios 的默认标头,如下所示:
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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4161 次 |
| 最近记录: |