axios传输json
时间: 2023-10-14 10:00:48 浏览: 181
回答: 使用axios传输JSON数据时,可以使用post方法,并设置请求头的Content-Type为application/json。首先,你需要在main.js中引入axios并将其定义为全局变量,可以使用以下代码:
```
import axios from 'axios'
Vue.prototype.$axios = axios
```
然后,在需要传值的地方使用以下代码:
```
this.$axios({
url: 'http://localhost:8087/creatClusterAndNodes',
method: "POST",
data: this.formdata,
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
console.log(res.data)
})
.catch(error => {
console.log(error)
})
```
在后台接收参数的Controller中,可以使用`@RequestBody`注解来接收JSON参数,例如:
```
@RequestMapping(value = "/creatClusterAndNodes", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String creatClusterAndNodes(@RequestBody JSONObject jsonParam) {
System.out.println("jsonParam:" + jsonParam);
return "okk";
}
```
另外,如果你想给Controller发送POST请求,应该将JSON对象转换成JSON格式字符串并设置请求头的Content-Type为application/json,可以参考以下代码:
```
var user = {
"id": this.id,
"username": this.username,
"password": this.password
}
axios({
url: 'http://127.0.0.1:81/user/user_add',
method: 'post',
data: user,
headers: {
'Content-Type': 'application/json'
}
})
```<span class="em">1</span><span class="em">2</span>
#### 引用[.reference_title]
- *1* [axios向springboot后台传递json数据](https://blog.csdn.net/David_house/article/details/124227767)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [用axios发送带json对象带post请求](https://blog.csdn.net/sonteki/article/details/114241959)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文