一.后端代码
import com.example.demo.pojo.Article;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/article")
@CrossOrigin//支持跨域
public class ArticleController {
private List<Article> articleList = new ArrayList<>();
{
articleList.add(new Article("医疗反腐绝非砍医护收入", "时事", "2023-09-5", "已发布"));
articleList.add(new Article("中国男篮缘何一败涂地", "篮球", "2023-09-5", "草稿"));
articleList.add(new Article("华山景区已受大风影响阵风达7-8级", "旅游", "2023-09-5", "已发布"));
}
//新增文章
@PostMapping("/add")
public String add(@RequestBody Article article) {
articleList.add(article);
return "新增成功";
}
//获取所有文章信息
@GetMapping("/getAll")
public List<Article> getAll(HttpServletResponse response) {
return articleList;
}
//根据文章分类和发布状态搜索
@GetMapping("/search")
public List<Article> search(String category, String state) {
return articleList.stream().filter(a -> a.getCategory().equals(category) && a.getState().equals(state)).collect(Collectors.toList());
}
}
二.前端调用axios
1>引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2>正常调用axios
(1)调用Get接口
<script>
/*发送请求*/
axios({
method:'get',
url:'http://localhost:8080/article/getAll'
}).then(result=>{//成功的回调
console.log(result.data)
}).catch(err=>{//失败的回调
console.log(err)
});
</script>
(2)调用post接口
<script>
/*发送请求*/
let article={
title:'明天会更好',
category:'生活',
time:'2000-01-01',
state:'草稿'
}
axios({
method:'post',
url:'http://localhost:8080/article/add',
data:article
}).then(result=>{//成功的回调
console.log(result.data)
}).catch(err=>{//失败的回调
console.log(err)
});
</script>
3>别名调用axios
(1)调用Get接口
<script>
/*发送请求*/
axios.get('http://localhost:8080/article/getAll').then(result=>{//成功的回调
console.log(result.data)
}).catch(err=>{//失败的回调
console.log(err)
});
</script>
(2)调用post接口
<script>
/*发送请求*/
let article={
title:'明天会更好',
category:'生活',
time:'2000-01-01',
state:'草稿'
}
axios.post('http://localhost:8080/article/add',article).then(result=>{//成功的回调
console.log(result.data)
}).catch(err=>{//失败的回调
console.log(err)
});
</script>