415是badrequest错误的请求,出现这种错误一般有如下几种情况
1:后台要求post方法,前端用了get请求,或者其他类似情况
2:请求的参数不对
3:Content-Type不对
前端代码如下:
'''
<template>
<div id="add_blog">
<h2>添加博客</h2>
<form>
<label>博客标题</label>
<input type="text" v-model="blog.title" required/>
<label>博客内容</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>博客标题: {{blog.title}}</p>
<p>博客内容:</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>
//这里设置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("请求失败了哦")
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>'''
后台接口
'''
@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
解决
网友评论