在Vue项目中使用axios的时候显示“not found get“或“not found post “ , “not found axios“等报错的解决办法

本文介绍了如何在Vue.js项目中设置全局的axios实例,通过Vue.prototype.$axios,实现API请求。首先,在main.js文件中,将axios绑定到Vue的原型链上,这样可以在组件中直接通过this.$axios访问。然后展示了使用this.$axios发起GET请求读取JSON文件的示例代码,并处理了响应成功和失败的情况。这种方式避免了与已有数据和方法的冲突。
摘要由CSDN通过智能技术生成

在 main.js 里面加上这一句

Vue.prototype.$axios = axios

然后项目中使用写上 this.$axios 开头即可

 this.$axios.get('../../public/Json/PrivacyPolicy.json')
        .then(function (response) {
          alert(response)
        })
        .catch(function (error) {
          console.log(error)
        })

提示:Vue.prototype 是定义一个Vue的原型链,自定义的名字前要加上 $ 这个符号,可以避免和已被定义的数据、方法、计算属性产生冲突。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的实现过程。 前端部分: 1. 使用 Vue CLI 创建一个新项目,然后安装 Element UI、AxiosVue Router。 ``` vue create my-project cd my-project npm install element-ui axios vue-router --save ``` 2. 在 `src` 目录下创建一个 `views` 文件夹,里面放置一个 `Comment.vue` 组件。 ```vue <template> <div> <div class="comment-header"> <h3>评论</h3> <el-button type="primary" @click="showForm = true">添加评论</el-button> </div> <div class="comment-body"> <el-card v-for="comment in comments" :key="comment.id"> <div class="comment-info"> <span class="comment-author">{{ comment.author }}</span> <span class="comment-date">{{ comment.date }}</span> </div> <div class="comment-content">{{ comment.content }}</div> <div class="comment-actions"> <el-button size="small" type="text" @click="editComment(comment)">编辑</el-button> <el-button size="small" type="text" @click="deleteComment(comment)">删除</el-button> <el-button size="small" type="text" @click="likeComment(comment)"> {{ comment.likes }} <i class="el-icon-thumb-up"></i> </el-button> </div> </el-card> </div> <el-dialog title="添加评论" :visible.sync="showForm" width="50%" center> <el-form :model="newComment" label-width="80px"> <el-form-item label="用户名"> <el-input v-model="newComment.author"></el-input> </el-form-item> <el-form-item label="评论内容"> <el-input type="textarea" v-model="newComment.content"></el-input> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="showForm = false">取消</el-button> <el-button type="primary" @click="addComment">确定</el-button> </div> </el-dialog> </div> </template> <script> import axios from 'axios'; export default { name: 'Comment', data() { return { comments: [], showForm: false, newComment: { author: '', content: '' } }; }, methods: { fetchComments() { axios.get('/api/comments').then(response => { this.comments = response.data; }).catch(error => { console.log(error); }); }, addComment() { axios.post('/api/comments', this.newComment).then(response => { this.comments.push(response.data); this.newComment.author = ''; this.newComment.content = ''; this.showForm = false; }).catch(error => { console.log(error); }); }, editComment(comment) { // TODO }, deleteComment(comment) { axios.delete(`/api/comments/${comment.id}`).then(response => { const index = this.comments.indexOf(comment); this.comments.splice(index, 1); }).catch(error => { console.log(error); }); }, likeComment(comment) { axios.post(`/api/comments/${comment.id}/like`).then(response => { comment.likes = response.data.likes; }).catch(error => { console.log(error); }); } }, mounted() { this.fetchComments(); } }; </script> <style scoped> .comment-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; } .comment-info { display: flex; justify-content: space-between; margin-bottom: 8px; } .comment-author { font-weight: bold; } .comment-date { color: #999; } .comment-content { margin-bottom: 8px; } .comment-actions { display: flex; justify-content: flex-end; } </style> ``` 3. 在 `src` 目录下创建一个 `router` 文件夹,里面放置一个 `index.js` 路由配置文件。 ```js import Vue from 'vue'; import VueRouter from 'vue-router'; import Comment from '@/views/Comment.vue'; Vue.use(VueRouter); const routes = [ { path: '/', name: 'Comment', component: Comment } ]; const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }); export default router; ``` 4. 在 `src` 目录下创建一个 `main.js` 入口文件,里面配置 Axios 和 Element UI。 ```js import Vue from 'vue'; import App from './App.vue'; import router from './router'; import axios from 'axios'; import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.config.productionTip = false; axios.defaults.baseURL = 'http://localhost:8080'; Vue.prototype.$http = axios; Vue.use(ElementUI); new Vue({ router, render: h => h(App) }).$mount('#app'); ``` 5. 创建一个 `public` 文件夹,里面放置一个 `index.html` 文件,用于渲染 Vue 应用。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Project</title> </head> <body> <div id="app"></div> <script src="/dist/js/chunk-vendors.js"></script> <script src="/dist/js/app.js"></script> </body> </html> ``` 后端部分: 1. 使用 Spring Initializr 创建一个新项目,然后添加 Spring Web、Spring Data JPA 和 H2 Database 的依赖。 2. 在 `src/main/java` 目录下创建一个 `com.example.myproject` 包,里面放置一个 `MyProjectApplication.java` 入口文件。 ```java package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyProjectApplication { public static void main(String[] args) { SpringApplication.run(MyProjectApplication.class, args); } } ``` 3. 在 `src/main/java` 目录下创建一个 `com.example.myproject.controller` 包,里面放置一个 `CommentController.java` 控制器,用于处理评论相关的 API 请求。 ```java package com.example.myproject.controller; import com.example.myproject.entity.Comment; import com.example.myproject.repository.CommentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import java.util.List; @RestController @RequestMapping("/api/comments") public class CommentController { @Autowired private CommentRepository commentRepository; @GetMapping public List<Comment> getAllComments() { return commentRepository.findAll(); } @PostMapping public Comment createComment(@RequestBody Comment comment) { return commentRepository.save(comment); } @PutMapping("/{id}") public ResponseEntity<Comment> updateComment(@PathVariable Long id, @RequestBody Comment comment) { Comment existingComment = commentRepository.findById(id).orElse(null); if (existingComment == null) { return ResponseEntity.notFound().build(); } existingComment.setAuthor(comment.getAuthor()); existingComment.setContent(comment.getContent()); Comment updatedComment = commentRepository.save(existingComment); return ResponseEntity.ok(updatedComment); } @DeleteMapping("/{id}") public ResponseEntity<Comment> deleteComment(@PathVariable Long id) { Comment comment = commentRepository.findById(id).orElse(null); if (comment == null) { return ResponseEntity.notFound().build(); } commentRepository.delete(comment); return ResponseEntity.ok(comment); } @Transactional @PostMapping("/{id}/like") public ResponseEntity<Comment> likeComment(@PathVariable Long id) { Comment comment = commentRepository.findById(id).orElse(null); if (comment == null) { return ResponseEntity.notFound().build(); } comment.setLikes(comment.getLikes() + 1); Comment updatedComment = commentRepository.save(comment); return ResponseEntity.ok(updatedComment); } } ``` 4. 在 `src/main/java` 目录下创建一个 `com.example.myproject.entity` 包,里面放置一个 `Comment.java` 实体类,用于表示评论。 ```java package com.example.myproject.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date; @Entity public class Comment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String author; private String content; private Integer likes = 0; private Date date = new Date(); public Comment() {} public Comment(String author, String content) { this.author = author; this.content = content; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getLikes() { return likes; } public void setLikes(Integer likes) { this.likes = likes; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } ``` 5. 在 `src/main/java` 目录下创建一个 `com.example.myproject.repository` 包,里面放置一个 `CommentRepository.java` 接口,用于与数据库交互。 ```java package com.example.myproject.repository; import com.example.myproject.entity.Comment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CommentRepository extends JpaRepository<Comment, Long> { } ``` 6. 在 `src/main/resources` 目录下创建一个 `application.properties` 配置文件,用于配置 H2 Database。 ``` spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.show-sql=true spring.h2.console.enabled=true spring.h2.console.path=/h2-console ``` 7. 运行项目,访问 `http://localhost:8080/h2-console` 可以进入 H2 Database 控制台,查看评论表的数据。 8. 运行项目,访问 `http://localhost:8080/` 可以进入 Vue 应用,查看评论区的界面效果。 以上就是一个简单的基于 Vue 和 Spring Boot 的评论区模块的实现过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值