今天遇到了网络请求的问题因为我要发送一个多参数的post请求,发现不能使用@requestmapping,
于是我改为使用@PostMapping但是其中不包含参数@Requestparam只包含@RequestBody
导致问题迟迟无法解决,
最后我改为使用get请求,用@GetMapping用@RequestParam实现参数传递。
<template> <div> <h1>文章</h1> <ul id="articles"> <li v-for="article in articles" :key="article.id"> {{ article.title }} - {{ article.content }} <button @click="deleteArticle(article.id)">删除</button> <button @click="editArticle(article)">编辑</button> </li> </ul> <form @submit.prevent="createArticle"> <input type="text" v-model="newArticle.title" placeholder="标题"> <textarea v-model="newArticle.content" placeholder="内容"></textarea> <button type="submit">创建</button> </form> <form v-if="editArticleId" @submit.prevent="updateArticle"> <input type="text" v-model="editArticle.title" placeholder="标题"> <textarea v-model="editArticle.content" placeholder="内容"></textarea> <button type="submit">更新</button> </form> </div> </template> <script> export default { data() { return { articles: [], newArticle: { title: '', content: '' }, editArticleId: null, editArticle: null } }, mounted() { this.getArticles(); }, methods: { getArticles() { axios.get('/api/articles') .then(response => { this.articles = response.data; }) .catch(error => { console.error(error); }); }, createArticle() { axios.post('/api/articles', this.newArticle) .then(response => { this.articles.push(response.data); this.newArticle = { title: '', content: '' }; }) .catch(error => { console.error(error); }); }, deleteArticle(id) { axios.delete(`/api/articles/${id}`) .then(response => { this.articles = this.articles.filter(article => article.id !== id); }) .catch(error => { console.error(error); }); }, editArticle(article) { this.editArticleId = article.id; this.editArticle = article; }, updateArticle() { axios.put(`/api/articles/${this.editArticleId}`, this.editArticle) .then(response => { this.articles = this.articles.map(article => { if (article.id === this.editArticleId) { return response.data; } else { return article; } }); this.editArticleId = null; this.editArticle = null; }) .catch(error => { console.error(error); }); } } }; </script>
@RestController @RequestMapping("/api/articles") public class ArticleController { @Autowired private ArticleRepository articleRepository; @GetMapping public List<Article> getAllArticles() { return articleRepository.findAll(); } @GetMapping("/{id}") public Article getArticleById(@PathVariable Long id) { return articleRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Article not found: " + id)); } @PostMapping public Article createArticle(@RequestBody Article article) { return articleRepository.save(article); } @PutMapping("/{id}") public Article updateArticle(@PathVariable Long id, @RequestBody Article article) { article.setId(id); return articleRepository.save(article); } @DeleteMapping("/{id}") public void deleteArticle(@PathVariable Long id) {
标签:articles,第六十二篇,return,response,2024,error,article,id From: https://www.cnblogs.com/xuechenhao173/p/18231492