我正在尝试使用 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
使用直接 axios
API 怎么样?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
来源:axios api
您可以使用邮递员生成代码。看看这张图片。按照步骤 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);
您可以使用以下内容传递原始文本。
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
是您传递请求正文的位置。
body
?
关键是使用@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);
}
如果有帮助,您还可以使用查询参数进行 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 中测试/模拟变得更容易
Authorization
标头不计在内,因为它已经在问题中了)?
我遇到了同样的问题。所以我查看了 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。
要在正文中发送表单数据,您可以像这样 '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',
},
})
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
}]
})
当我尝试以原始 json 格式在正文中发送身份验证凭据时,这对我来说效果很好。
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
不定期副业成功案例分享