Axios发送Delete请求自定义Header失效引发406错误求助
问题:DELETE请求返回406 Not Acceptable错误,其余请求正常
我开发了一个CRUD应用,采用JSON:API格式的API接口。调用DELETE方法时持续返回406(Not Acceptable)错误,其余请求方法均可正常传递自定义Header,仅DELETE请求异常。相关代码及API终端报错信息如下:
相关代码
axios.js
import axios from 'axios'; const api = axios.create({ baseURL: 'http://localhost:3000', }); export default api;
headers.js
import api from './axios'; const authHeader = { headers: { Accept: 'application/vnd.api+json', 'content-type': 'application/vnd.api+json', }, }; const body = { body: { name: 'Vitor Queiroz', }, }; async function getAuth() { return api.post('/auths', body, authHeader).then((response) => { return response.data.token; }); } const headers = { headers: { Accept: 'application/vnd.api+json', 'content-type': 'application/vnd.api+json', authorization: `Bearer ${await getAuth()}`, }, }; export default headers;
editUnit.vue中Delete方法代码(第68-86行)
deleteUnit(id) { const body = { id: `${id}`, }; api .delete(`/units/${id}`, { data: { headers } }) .then((res) => { console.log(id); if (res.status == 204) { this.status = '204'; } }) .catch( (err) => ( (this.error = err.response.status), (this.status = err.response.status) ) ); }
API终端报错信息
Started DELETE "/units/7" for 127.0.0.1 at 2022-08-16 15:02:33 -0300 Processing by UnitsController#destroy as HTML Parameters: {"id"=>"7"} Filter chain halted as :ensure_json_request rendered or redirected Completed 406 Not Acceptable in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms | Allocations: 87)
问题原因及解决办法
从报错信息可见,服务器将DELETE请求识别为HTML格式处理,但接口要求JSON:API格式,核心问题是DELETE请求的headers传递方式错误。
在axios的delete方法中,第二个参数是配置对象,你错误地把headers嵌套到了data字段里,导致自定义的Accept和Content-Type头并未传递到服务器。
修改editUnit.vue中的deleteUnit方法:
deleteUnit(id) { api .delete(`/units/${id}`, headers) // 直接传入headers配置,无需放到data中 .then((res) => { console.log(id); if (res.status == 204) { this.status = '204'; } }) .catch( (err) => { this.error = err.response.status; this.status = err.response.status; } ); }
额外说明:DELETE请求通常不需要请求体,你之前定义的body字段可以移除,JSON:API规范下的DELETE接口一般仅需通过URL传递资源ID即可。
内容的提问来源于stack exchange,提问作者VQV03
相关产品推荐
相关产品推荐

