[英]Why Content-Type “appication/json” is not Working when method is “GET” in axios?
[英]Why is Axios not using the Content-Type header and converting the request method to GET when PATCHing to a specific URL?
我繼承了使用 Axios 的代碼庫,否則我對該庫不熟悉。 這是一個 Node 應用程序,我正在嘗試向第三方 API 發送 PATCH 請求。 Axios 使用以下配置:
const axios = require('axios').create({
baseURL: process.env.API_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
auth: {
username: process.env.API_USER,
password: process.env.API_PW,
},
});
然后我嘗試發出以下 PATCH 請求:
const data = {
fields: {
field_a: 'yes',
field_b: 'no',
},
};
try {
const res = await axios.patch(`/user/${user.id}`, data, {
headers: {
'Content-Type': 'application/json'
}
});
return res;
} catch (err){
console.error(err);
}
據我所知,我只是在進行補丁調用時重新定義了 Content-Type header,但這只是試圖解決這個問題。 這兩種方式都行不通。 我在響應對象的 config 屬性中看到的內容如下(大部分都被排除在外):
{
headers: {
Accept: "application/json"
User-Agent: "axios/0.19.0"
},
method: 'patch',
}
查看同一響應 object 的請求屬性,我看到那里的方法被列為“GET”,內容類型 header 也沒有在那里列出。 似乎 Content-Type header 正在被剝離,並且方法正在更改為 GET。
如果我只將 URL 目標更改為/userWRONGPATH/${user.id}
,我會收到預期的 404 響應,但響應對象的配置數據包括以下內容:
{
headers: {
Accept: "application/json"
Content-Length: 105
Content-Type: "application/json"
User-Agent: "axios/0.19.0"
}
}
響應對象的請求方法現在是預期的“PATCH”。 如果這實際上是這里發生的事情,我不確定為什么補丁方法適用於其他路徑。
您好,我認為問題可能與在 Axios 中再次發送 header 相關,您定義了一個配置並將其添加到所有請求中。
這是我使用 axios 訂購項目的示例。
// Axios custom config
const axiosInstance = axios.create({
baseURL: urlBase,
// timeout: 1000,
headers: { 'Content-type': 'application/json' },
});
export const apiPatchRequest = (url, id, obj) => (
axiosInstance.patch(`${url}/${id}`, obj)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.