ChatGPT解决这个技术问题 Extra ChatGPT

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

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

这里我添加了内容类型部分。但是我怎样才能添加身体部分呢?

谢谢你。

编辑:

https://i.stack.imgur.com/JXftu.png


U
Ukasha

使用直接 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 正文
r
reza jafari

您可以使用邮递员生成代码。看看这张图片。按照步骤 1 和步骤 2。

https://i.stack.imgur.com/tpaJH.png

如果您的端点只接受通过 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);

我来这篇文章是为了帮助回答,我刚刚学到了一些新东西..我从来没有注意到甚至没有点击过代码片段按钮,而且我使用邮递员的时间已经超出了我的记忆范围.. +1
A
Armand

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

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' 的方式
O
Ogglas

关键是使用@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 http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

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


T
TheZ

这是我的解决方案:

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

这应该有帮助


J
Jeffery Sidhu

你可以像这样传递参数

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

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


-1 您的回答与@Uddesh_jain 的回答有何不同(除了 Authorization 标头不计在内,因为它已经在问题中了)?
h
hahaha

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


s
s-hunter

要在正文中发送表单数据,您可以像这样 'grant_type=client_credentials&client_id=12345&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',
    },
})

K
Keshav Gera
axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});

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

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

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

Q
Query

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

A
Atiq Baqi

当我尝试以原始 json 格式在正文中发送身份验证凭据时,这对我来说效果很好。

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