【问题标题】:How can I add raw data body to an axios request?如何将原始数据主体添加到 axios 请求?
【发布时间】:2018-12-27 03:59:07
【问题描述】:

我正在尝试使用 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);
    });

这里我添加了内容类型部分。但是如何添加body部分呢?

谢谢。

编辑:

这是工作邮递员请求的屏幕截图

【问题讨论】:

    标签: javascript c# reactjs post axios


    【解决方案1】:

    直接使用axios API 怎么样?

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

    来源:axios api

    【讨论】:

    • 这不是表示数据部分是作为 JSON 发送的吗?
    • 我们如何获取数据:从反应表单?例如:用户提供输入,然后我们可以使用输入的数据生成 json 正文
    【解决方案2】:

    您可以使用以下内容传递原始文本。

    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 是您传递请求正文的地方。

    【讨论】:

    • 我不知道为什么,但这不起作用。你能看看我添加的截图吗?也许我错过了什么。
    • @KarimTaha 您是否尝试过添加整个文本来代替body
    • 这就是在 axios 中没有表单字段名称的情况下执行 curl -d 'some data to send' 的方式
    【解决方案3】:

    这是我的解决方案:

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

    这应该会有所帮助

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题。所以我查看了 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。

      【讨论】:

        【解决方案5】:
        axios({
          method: 'post',     //put
          url: url,
          headers: {'Authorization': 'Bearer'+token}, 
          data: {
             firstName: 'Keshav', // This is the body part
             lastName: 'Gera'
          }
        });
        

        【讨论】:

        • 如果您提供解释为什么这是首选解决方案并解释它是如何工作的,它会更有帮助。我们想要教育,而不仅仅是提供代码。
        • 数据部分在这里作为 JSON 而不是简单的字符串发送
        【解决方案6】:

        有许多方法可以通过post 请求发送原始数据。我个人喜欢这个。

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

        【讨论】:

          【解决方案7】:

          我发现唯一可行的解​​决方案是 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
                  }]
              })
          

          【讨论】:

            【解决方案8】:

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

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

            如果您使用.NET,需要注意的是,控制器的原始字符串将返回415 Unsupported Media Type。为了解决这个问题,您需要像这样将原始字符串封装在连字符中并将其发送为"Content-Type": "application/json"

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

            C# 控制器:

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

            这将发布一个带有两个查询参数的空正文:

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

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

            【讨论】:

              【解决方案9】:

              你可以像这样传递参数

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

              这也使得在 Jest 中测试/模拟变得更容易

              【讨论】:

              • -1 您的回答与@Uddesh_jain 的回答有何不同(Authorization 标头除外,因为它已经在问题中了)?
              【解决方案10】:

              您可以使用邮递员生成代码。看看这张图片。按照第 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);
              

              【讨论】:

              • 我来这篇文章是为了帮助回答,我刚刚学到了一些新东西。我从来没有注意到甚至点击了代码 sn-p 按钮,我一直在使用邮递员来获取更多信息我不记得了.. +1
              【解决方案11】:

              要在正文中发送表单数据,您可以像这样'grant_type=client_credentials&amp;client_id=12345&amp;client_secret=678910' 将数据格式化为 url 参数并将其附加到 axios 配置中的数据。

              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',
                  },
              })
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-02-09
                • 1970-01-01
                • 1970-01-01
                • 2020-09-01
                • 2019-10-30
                • 2022-12-17
                • 2019-10-11
                • 2012-10-22
                相关资源
                最近更新 更多