簡體   English   中英

在 React TS 中使用 Axios 發送 Post 數據

[英]Send Post Data by using Axios in React TS

目標:
使用 Axios 將帖子從客戶端發送到后端

問題:
Axios 代碼無法將數據發送到后端,而 fetch 代碼可以做到。

與 axios 相關的數據在后端將是 id = 0 和 firstname = null

當我使用獲取代碼時效果很好,我可以在后端看到它

主要區別在於“請求 Header > 接受”(看圖片)。

我應該如何在“Request Header > Accept”處啟用“ / ”而不是 Application/json、text/plain、 /

謝謝!


const params = { 
  id: 1,
  firstName: "sdf"
}

var config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  accept: { }
};

axios.post('http://localhost:1122/api/v1/Test/AddClient', params, config)
.then(response => {
})
.catch(error => {
  console.log(error.response)}
);
 

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var urlencoded = new URLSearchParams();
urlencoded.append("id", "1");
urlencoded.append("firstName", "sdf");

let requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded
};

fetch("http://localhost:1122/api/v1/Test/AddClient", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

在此處輸入圖像描述

在此處輸入圖像描述

Accept 是 header 將 accept 的值更改為“ / ” 您需要將其添加到請求標頭中 您正確創建了配置 object 但接受應該在標頭中

var config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'accept': '*/*',
  },
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM