简体   繁体   English

如何将原始数据主体添加到 axios 请求?

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

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.我正在尝试使用 Axios 从我的 React 应用程序与 API 进行通信。我设法使 GET 请求正常工作,但现在我需要一个 POST 请求。

I need the body to be raw text, as I will write an MDX query in it.我需要正文是原始文本,因为我将在其中编写 MDX 查询。 Here is the part where I make the request:这是我提出请求的部分:

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);
    });

Here I added the content type part.这里我添加了内容类型部分。 But how can I add the body part?但是我怎样才能添加正文部分呢?

Thank you.谢谢你。

Edit:编辑:

Here is a screenshot of the working Postman request这是工作 Postman 请求的屏幕截图邮递员工作要求

How about using direct axios API?直接用axios API怎么样?

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

Source: axios api来源: axios api

You can use postman to generate code.您可以使用 postman 生成代码。 Look at this image.看看这张图片。 Follow step1 and step 2.按照步骤 1 和步骤 2。

在此处输入图像描述

If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.如果您的端点只接受通过 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);

You can use the below for passing the raw text.您可以使用以下内容传递原始文本。

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);
});

Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body .只需将您的原始文本放在body中,或直接在引号中作为'raw text to be sent'代替body传递。

The signature of the axios post is axios.post(url[, data[, config]]) , so the data is where you pass your request body. axios 帖子的签名是axios.post(url[, data[, config]]) ,因此data是您传递请求正文的地方。

The key is to use "Content-Type": "text/plain" as mentioned by @MadhuBhat.关键是使用@MadhuBhat 提到的"Content-Type": "text/plain"

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

A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type .如果您使用.NET ,需要注意的是,到 controller 的原始字符串将返回415 Unsupported Media Type To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json" :为了解决这个问题,您需要像这样将原始字符串封装在连字符中并将其作为"Content-Type": "application/json"发送:

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

C# Controller: 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 https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

You can also make a POST with query params if that helps:如果有帮助,您还可以使用查询参数进行 POST:

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

This will POST an empty body with the two query params:这将发布一个带有两个查询参数的空正文:

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

Source: https://stackoverflow.com/a/53501339/3850405来源: https://stackoverflow.com/a/53501339/3850405

Here is my solution:这是我的解决方案:

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);
});

This should help这应该有帮助

You can pass the params like so你可以像这样传递参数

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

this makes it easier to test/mock in Jest as well这也使得在 Jest 中测试/模拟变得更容易

I got same problem.我遇到了同样的问题。 So I looked into the axios document.所以我查看了 axios 文档。 I found it.我找到了。 you can do it like this.你可以这样做。 this is easiest way.这是最简单的方法。 and super simple.超级简单。

https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format 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);

You can use.then,.catch.你可以使用.then,.catch。

For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.要在正文中发送表单数据,您只需格式化 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'
  }
});

There many methods to send raw data with a post request.有许多方法可以通过post请求发送原始数据。 I personally like this one.我个人喜欢这个。

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

The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.我发现唯一可行的解​​决方案是 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
        }]
    })

Original reference from axios.post on Github . 来自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);
  });

And the additional parameters of request should go as 3-rd argument (eg like in this Issue snippet ): 并且请求的其他参数应该作为第3个参数(例如, 在此问题代码段中 ):

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

The format for an axios request is as following: axios请求的格式如下:

axios.post(url[, data[, config]]); axios.post(url [,data [,config]]); the body can be passed in data, headers can be passed in config. 正文可以在数据中传递,标题可以在config中传递。

This worked fine for me when trying to send authentication credential in body in raw json format.当我尝试以原始 json 格式在正文中发送身份验证凭据时,这对我来说效果很好。

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

Used in React jsReact 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); })

For me this solution works, ie JSON.stringify(your data) , just convert your raw data using JSON.stringify method.对我来说,这个解决方案有效,即JSON.stringify(your data) ,只需使用JSON.stringify方法转换原始数据。

I hope this works.我希望这有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM