415是badrequest錯(cuò)誤的請(qǐng)求妒御,出現(xiàn)這種錯(cuò)誤一般有如下幾種情況
1:后臺(tái)要求post方法盼铁,前端用了get請(qǐng)求悄晃,或者其他類似情況
2:請(qǐng)求的參數(shù)不對(duì)
3:Content-Type不對(duì)
前端代碼如下:
'''
<template>
<div id="add_blog">
<h2>添加博客</h2>
<form>
<label>博客標(biāo)題</label>
<input type="text" v-model="blog.title" required/>
<label>博客內(nèi)容</label>
<textarea v-model="blog.content"></textarea>
<div id="checkboxes">
<label>Vue.js</label>
<input type="checkbox" value="Vue.js" />
<label>Node.js</label>
<input type="checkbox" value="Node.js" />
<label>React.js</label>
<input type="checkbox" value="React.js" />
<label>Angular4.js</label>
<input type="checkbox" value="Angular4.js"/>
</div>
<label>作者</label>
<select v-model="blog.author">
<option v-for="author in authors" :key="author">
{{author}}
</option>
</select>
<button v-on:click.prevent="add">添加博客</button>
</form>
<div id="preview">
<h3>博客總覽</h3>
<p>博客標(biāo)題: {{blog.title}}</p>
<p>博客內(nèi)容:</p>
<p>{{blog.content}}</p>
<p>博客分類:</p>
<ul>
<li v-for="category in blog.categories" :key="category">
{{category}}
</li>
</ul>
<p>作者: {{blog.author}}</p>
</div>
</div>
</template>
<script>
//這里設(shè)置Content-Type問題解決
import axios from 'axios'
axios.defaults.headers.post['Content-Type']='application/json'
export default {
name:"add_blog",
data(){
return {
blog:{
id:"",
title:"",
content:"",
categories:"abc",
author:""
},
authors:["zg","sg","nb"]
}
},
methods: {
add:function(){
console.log("blog==>"+JSON.stringify(this.blog));
axios.post('http://localhost:8888/blog/add',JSON.stringify(this.blog)
) .then(function(response){
console.log(response)
}) .catch(function(error){
alert("請(qǐng)求失敗了哦")
console.log(error)
});
}
}
}
</script>
<style scoped>
add-blog *{
box-sizing: border-box;
}
add-blog{
margin: 20px auto;
max-width: 600px;
padding: 20px;
}
label{
display: block;
margin: 20px 0 10px;
}
input[type="text"],textarea,select{
display: block;
width: 100%;
padding: 8px;
}
textarea{
height: 200px;
}
checkboxes label{
display: inline-block;
margin-top: 0;
}
checkboxes input{
display: inline-block;
margin-right: 10px;
}
button{
display: block;
margin: 20px 0;
background: crimson;
color: #fff;
border: 0;
padding: 14px;
border-radius: 4px;
font-size: 18px;
cursor: pointer;
}
preview{
padding: 10px 20px;
border: 1px dotted #ccc;
margin: 30px 0;
}
h3{
margin-top: 10px;
}
</style>'''
后臺(tái)接口
'''
@ApiOperation(value="添加博客",notes ="添加博客")
@RequestMapping(value="/add",method = RequestMethod.POST)
@CrossOrigin
public ResponseEntity<BaseMsg> addBlog(@RequestBody Blog blog){
BaseMsg baseMsg=new BaseMsg();
try {
blogService.addBlog(blog);
}catch (Exception e){
baseMsg.setCode(1);
baseMsg.setMsg("failed");
}finally {
return ResponseEntity.ok(baseMsg);
}
}
'''
這里在前端通過代碼
axios.defaults.headers.post['Content-Type']='application/json
解決