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

103

我正在使用Axios从我的React应用程序与API进行通信。我已经成功地完成了GET请求,但现在需要一个POST请求。

我需要body为原始文本,因为我将在其中编写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 请求截图Postman working request

14个回答

113

使用直接的axios API如何?

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

来源: axios api


44
这是否意味着数据部分将以JSON格式发送? - Karim Taha
如何获取来自React表单的数据?例如:用户提供输入,然后我们可以使用输入的数据生成JSON主体。 - JayC
@KarimTaha,我们发送到服务器的格式除了json还需要什么吗? - Timo

71
你可以使用Postman来生成代码。查看这张图片,按照步骤1和步骤2操作即可。 enter image description here 如果你的端点只接受通过Body(在Postman中)发送的数据,那么你应该发送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", formdata);

10
我来到这篇帖子是要帮助回答问题的,但我刚学到了一些新东西..我从来没有注意过或者点击过代码片段按钮,而我已经使用Postman很久了..+1 - Dany Balian
1
最佳解决方案,适用于任何情况,谢谢 :pray: - Naeem Baghi
1
从来不知道邮递员可以生成代码。这对我来说真是救星。非常感谢! - Shreehari

31
您可以使用下面的内容传递原始文本。
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 中,或者直接在引号中传递 '要发送的原始文本',以取代 body

axios post 的签名是 axios.post(url[, data[, config]]),因此 data 是您传递请求正文的位置。


我不知道为什么这个不起作用。你能看一下我添加的截图吗?也许我漏掉了什么。 - Karim Taha
@KarimTaha 你尝试过将整个文本替换掉“body”吗? - Madhu Bhat
1
这是如何在axios中执行curl -d 'some data to send'而不使用表单字段名称的方法。 - Eric

12
关键在于使用@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));

这将使用两个查询参数POST一个空主体:

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

来源:https://dev59.com/tlQJ5IYBdhLWcg3wl3Fa#53501339


"Content-Type": "text/plain" 这个提示正是我所需要的。 - Gabriel Arghire

9

这是我的解决方案:

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

这应该能帮到你


5
您可以这样传递参数。
await axios.post(URL, {
  key:value //Second param will be your body
},
{
headers: {
  Authorization: ``,
  'Content-Type': 'application/json'
}

这样做可以更方便地在Jest中进行测试/模拟


除了“Authorization”标头(因为它已经在问题中),您的答案与@Uddesh_jain的答案有什么不同? - Tino

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。

3

如果想要在请求主体中发送表单数据,你只需按以下方式将数据格式化为url参数:'grant_type=client_credentials&client_id=12345&client_secret=678910'并附加到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',
    },
})

2

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

2

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

感谢分享 transformRequest 选项。我正在测试一个 API 并想故意向服务器发送损坏的 JSON 数据。你的答案带我找到了正确的解决方案。 - line-o

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接