Javascript Axios将常量名称作为大纲添加到JSON中,如何仅发送正文?
我正在尝试向我创建的RESTAPI发送POST请求。POST请求是从Reactjs应用程序发送的 我要发送的JSON如下所示:Javascript Axios将常量名称作为大纲添加到JSON中,如何仅发送正文?,javascript,json,reactjs,axios,Javascript,Json,Reactjs,Axios,我正在尝试向我创建的RESTAPI发送POST请求。POST请求是从Reactjs应用程序发送的 我要发送的JSON如下所示: { "name":"something" } const json = { "name" : "something" } Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json}
{
"name":"something"
}
const json = {
"name" : "something"
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json})
.then(res => {
console.log(res);
console.log(res.data);
})
{
"json"{
"name":"something"
}
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {"name":"something"})
.then(res => {
console.log(res);
console.log(res.data);
})
我的计划是这样发送:
{
"name":"something"
}
const json = {
"name" : "something"
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json})
.then(res => {
console.log(res);
console.log(res.data);
})
{
"json"{
"name":"something"
}
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {"name":"something"})
.then(res => {
console.log(res);
console.log(res.data);
})
但当我这样做时,发送的JSON如下所示:
{
"name":"something"
}
const json = {
"name" : "something"
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json})
.then(res => {
console.log(res);
console.log(res.data);
})
{
"json"{
"name":"something"
}
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {"name":"something"})
.then(res => {
console.log(res);
console.log(res.data);
})
如果出现错误,则API无法处理该请求。有没有办法只发送常量的体?我知道我可以这样发送请求:
{
"name":"something"
}
const json = {
"name" : "something"
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json})
.then(res => {
console.log(res);
console.log(res.data);
})
{
"json"{
"name":"something"
}
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {"name":"something"})
.then(res => {
console.log(res);
console.log(res.data);
})
这是可行的,但我想发送比一行硬编码更复杂的JSON。那么,有没有解决这个问题的好方法呢?{}是一个新对象
{json}是一个新对象,其属性名为json,该属性的值与同名变量的值相同
如果您不想将数据包装到新对象中,请不要这样做
Axios.post("http://localhost:8080/BackendWiki/api/brands/", json)
注意:json变量的值是一个对象。它只有在Axios库中的某个地方才能转换为JSON。您可能应该给它一个更具描述性的名称,例如brand。删除包装对象引用的{}。数据参数需要一个对象,而json已经是一个对象了
请注意,这是一个糟糕的变量名选择,因为它实际上不是json数据,而json数据是字符串数据格式
Axios.post("http://localhost:8080/BackendWiki/api/brands/", json)
在Axios.post调用中,通过将json{}包装在括号中,可以创建一个嵌套的json对象。移除这些应该可以解决问题。谢谢,这就解决了问题!变量名只是为这个问题创建的,不会在应用程序中使用。请使用json而不是对象文本{json:json}的缩写{json}