簡體   English   中英

如何將原始數據主體添加到 axios 請求?

[英]How can I add raw data body to an axios request?

我正在嘗試使用 Axios 從我的 React 應用程序與 API 進行通信。我設法使 GET 請求正常工作,但現在我需要一個 POST 請求。

我需要正文是原始文本,因為我將在其中編寫 MDX 查詢。 這是我提出請求的部分:

axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
    {
      headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
      'Content-Type' : 'text/plain' }
    }).then((response) => {
      this.setState({data:response.data});
      console.log(this.state.data);
    });

這里我添加了內容類型部分。 但是我怎樣才能添加正文部分呢?

謝謝你。

編輯:

這是工作 Postman 請求的屏幕截圖郵遞員工作要求

直接用axios API怎么樣?

axios({
  method: 'post',
  url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
  headers: {}, 
  data: {
    foo: 'bar', // This is the body part
  }
});

來源: axios api

您可以使用 postman 生成代碼。 看看這張圖片。 按照步驟 1 和步驟 2。

在此處輸入圖像描述

如果您的端點只接受通過 Body(在郵遞員中)發送的數據,您應該發送 FormData。

var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
      
let res = await axios.post("/api/save_rate", dataform);

您可以使用以下內容傳遞原始文本。

axios.post(
        baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan, 
        body, 
        {
            headers: { 
                'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
                'Content-Type' : 'text/plain' 
            }
        }
).then(response => {
    this.setState({data:response.data});
    console.log(this.state.data);
});

只需將您的原始文本放在body中,或直接在引號中作為'raw text to be sent'代替body傳遞。

axios 帖子的簽名是axios.post(url[, data[, config]]) ,因此data是您傳遞請求正文的地方。

關鍵是使用@MadhuBhat 提到的"Content-Type": "text/plain"

axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
    console.log(response);
});

如果您使用.NET ,需要注意的是,到 controller 的原始字符串將返回415 Unsupported Media Type 為了解決這個問題,您需要像這樣將原始字符串封裝在連字符中並將其作為"Content-Type": "application/json"發送:

axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
    console.log(response);
});

C# Controller:

[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
    return Ok(code);
}

https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

如果有幫助,您還可以使用查詢參數進行 POST:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

這將發布一個帶有兩個查詢參數的空正文:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

來源: https://stackoverflow.com/a/53501339/3850405

這是我的解決方案:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

這應該有幫助

你可以像這樣傳遞參數

await axios.post(URL, {
  key:value //Second param will be your body
},
{
headers: {
  Authorization: ``,
  'Content-Type': 'application/json'
}

這也使得在 Jest 中測試/模擬變得更容易

我遇到了同樣的問題。 所以我查看了 axios 文檔。 我找到了。 你可以這樣做。 這是最簡單的方法。 超級簡單。

https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

你可以使用.then,.catch。

要在正文中發送表單數據,您只需格式化 url 參數中的數據,例如'grant_type=client_credentials&client_id=12345&client_secret=678910' ,並將其附加到 Z38C3787939C7B0B6C17D73FCE3D28 的配置中的數據。

axios.request({
    method: 'post',
    url: 'http://www.example.com/',
    data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
})
axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});

有許多方法可以通過post請求發送原始數據。 我個人喜歡這個。

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)

我發現唯一可行的解​​決方案是 transformRequest 屬性,它允許您在發送請求之前覆蓋 axios 所做的額外數據准備。

    axios.request({
        method: 'post',
        url: 'http://foo.bar/',
        data: {},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        transformRequest: [(data, header) => {
            data = 'grant_type=client_credentials'
            return data
        }]
    })

來自Axis.post的原始參考在Github上

axios.post(`${baseUrl}applications/${appName}/dataexport/plantypes${plan}`, {
    mdxQuery: '<your_mdx_query>',
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

並且請求的其他參數應該作為第3個參數(例如, 在此問題代碼段中 ):

axios.post(`${baseUrl}applications/${appName}/dataexport/plantypes${plan},
   {
     mdxQuery: '<your_mdx_query>',
   },
   {
     headers: { 
       'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
       'Content-Type': 'text/plain'
     }
   }
);

axios請求的格式如下:

axios.post(url [,data [,config]]); 正文可以在數據中傳遞,標題可以在config中傳遞。

當我嘗試以原始 json 格式在正文中發送身份驗證憑據時,這對我來說效果很好。

let credentials = {
  username: "your-username",
  password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
  console.log(res.data);
})

React js中使用

let url = `${process.env.REACT_APP_API}/validuser`;

   let body = JSON.stringify({
     loginid: "admin",
     password: "admin",
  });

var authOptions = {
  method: "post",
  url: url,
  data: body,
  headers: {
    "Content-Type": "application/json",
  },
  json: true,
};

axios(authOptions)
  .then((resp) => {
    console.log("response :- ",resp);
  })
  .catch((error) => {
    alert(error);
  });

 let url='<your domain.extension>'; let data= JSON.stringify('mydata'); axios.get(url, { data }).then((res) => { console.log(res.data); })

對我來說,這個解決方案有效,即JSON.stringify(your data) ,只需使用JSON.stringify方法轉換原始數據。

我希望這有效。

暫無
暫無

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

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