我有一個小專案,我時不時地作業,我已經潛入我不熟悉的 Express 作為它的后端。出于某種原因,當我使用我的 DELETE 路由而不是 POST 時,正文沒有通過。
api.js是我用來發出請求的小型獲取庫:
import store from '@/store';
// API headers
const HEADERS = {
ALIAS: 'X-Organization-Alias',
AUTH: 'Authorization',
CACHE: 'Cache-Control',
ACCEPT: 'Accept',
CONTENT: 'Content-Type',
};
// HTTP codes
const CODES = {
AUTH_REQUIRED: 401,
};
const api = {
call: (method, url, input) => {
let path = `${store.state.endpoint}/${url}`;
return fetch(path, {
method,
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
mode: 'cors',
credentials: 'omit',
headers: {
[HEADERS.ALIAS]: 'web-client',
[HEADERS.CACHE]: 'no-cache',
[HEADERS.ACCEPT]: 'application/json',
[HEADERS.CONTENT]: 'application/json',
},
body: method === 'POST' || method === 'PATCH' ? JSON.stringify(input) : null,
})
.then((response) => {
if (!response.ok) {
switch (response.status) {
// Authorization requests do a hard refresh to the login page rather than route
// This is so that any state is safely purged
case CODES.AUTH_REQUIRED:
document.location.href = '/login';
break;
default:
console.log(response)
// TODO create error dialog/toast
}
throw new Error();
}
return response;
})
.then((response) => response.json())
},
get: (url, input) => api.call('GET', url, input),
post: (url, input) => api.call('POST', url, input),
patch: (url, input) => api.call('PATCH', url, input),
delete: (url, input) => api.call('DELETE', url, input)
}
export default api;
我提出如下要求:
api.delete('arena/entry', { arena_history_id: arena_history_id })
.then(response => {
if (response) {
this.saved_arenas = response;
}
})
以及快速路線上 req.body 中的一個空物件:
OPTIONS /arena/entry 200 2.435 ms - 20
{}
DELETE /arena/entry 200 2.488 ms - 29
如果我將請求更改為:
api.post('arena/entry', { arena_history_id: arena_history_id })
.then(response => {
if (response) {
this.saved_arenas = response;
}
})
我正確收到:
OPTIONS /arena/entry 200 2.353 ms - 20
{ arena_history_id: 13 }
POST /arena/entry 200 12.631 ms - 29
到底是怎么回事?
uj5u.com熱心網友回復:
DELETE請求不應該有正文。從最近更新的 HTTP 規范:
盡管請求訊息幀與使用的方法無關,但在 DELETE 請求中接收的內容沒有一般定義的語意,不能改變請求的含義或目標,并且可能導致某些實作拒絕請求并關閉連接,因為它的潛力作為請求走私攻擊([HTTP/1.1] 的第 11.2 節)。客戶端不應該在 DELETE 請求中生成內容,除非它是直接向源服務器發出的,該源服務器先前已在帶內或帶外指示此類請求有目的并且將得到充分支持。源服務器不應該依賴私有協議來接收內容,因為 HTTP 通信的參與者通常不知道請求鏈中的中介。
來源:https ://www.rfc-editor.org/rfc/rfc9110.html#section-9.3.5
如此多的服務器和客戶端只是放棄了主體,這在規范范圍內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489773.html
標籤:表示
