![](/img/trans.png)
[英]how can i receive the body of an axios post request with express nodejs?
[英]How can I add raw data body to an axios request?
我正在尝试使用 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);
});
这里我添加了内容类型部分。 但是我怎样才能添加正文部分呢?
谢谢你。
编辑:
直接用axios
API怎么样?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
来源: axios api
您可以使用 postman 生成代码。 看看这张图片。 按照步骤 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);
您可以使用以下内容传递原始文本。
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
是您传递请求正文的地方。
关键是使用@MadhuBhat 提到的"Content-Type": "text/plain"
。
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
如果您使用.NET
,需要注意的是,到 controller 的原始字符串将返回415 Unsupported Media Type
。 为了解决这个问题,您需要像这样将原始字符串封装在连字符中并将其作为"Content-Type": "application/json"
发送:
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[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
这是我的解决方案:
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 中测试/模拟变得更容易
我遇到了同样的问题。 所以我查看了 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。
要在正文中发送表单数据,您只需格式化 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'
}
});
有许多方法可以通过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
}]
})
来自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);
});
并且请求的其他参数应该作为第3个参数(例如, 在此问题代码段中 ):
axios.post(`${baseUrl}applications/${appName}/dataexport/plantypes${plan},
{
mdxQuery: '<your_mdx_query>',
},
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type': 'text/plain'
}
}
);
axios请求的格式如下:
axios.post(url [,data [,config]]); 正文可以在数据中传递,标题可以在config中传递。
当我尝试以原始 json 格式在正文中发送身份验证凭据时,这对我来说效果很好。
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
在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);
});
let url='<your domain.extension>'; let data= JSON.stringify('mydata'); axios.get(url, { data }).then((res) => { console.log(res.data); })
对我来说,这个解决方案有效,即JSON.stringify(your data)
,只需使用JSON.stringify
方法转换原始数据。
我希望这有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.