vue中如何獲取后台數據


需要引用vue-resource

安裝請參考https://github.com/pagekit/vue-resource官方文檔

在入口函數中加入

1
2
import VueResource from 'vue-resource'
Vue.use(VueResource);

在package.json文件中加入

1
2
3
4
"dependencies": {
    "vue": "^2.2.6",
    "vue-resource":"^1.2.1"
  },

請求如下

1
2
3
4
5
6
7
8
9
10
11
mounted: function () {
         // GET /someUrl
         this.$http.get('http://localhost:8088/test').then(response => {
              console.log(response.data);
             // get body data
             // this.someData = response.body;
 
         }, response => {
             console.log("error");
         });
     },

注意

1.在請求接口數據時,涉及到跨域請求 
出現下面錯誤: 
XMLHttpRequest cannot load http://localhost:8088/test. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access.

解決辦法:在接口中設置

1
response.setHeader("Access-Control-Allow-Origin", "*");

2.使用jsonp請求 

但是出現如下錯誤 
Uncaught SyntaxError: Unexpected token 
查看請求,數據已返回,未解決.

提交表單

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
   < div  id="app-7">
         < form  @submit.prevent="submit">
             < div  class="field">
                 姓名:
                 < input  type="text"
                        v-model="user.username">
             </ div >
 
 
             < div  class="field">
                 密碼:
                 < input  type="text"
                        v-model="user.password">
             </ div >
 
 
             < input  type="submit"
                    value="提交">
             </ form >
     </ div >
 
methods: {
         submit: function() {
           var formData = JSON.stringify(this.user); // 這里才是你的表單數據
 
           this.$http.post('http://localhost:8088/post', formData).then((response) => {
               // success callback
               console.log(response.data);
           }, (response) => {
                console.log("error");
               // error callback
           });
         }
     },

  

 

提交restful接口出現跨域請求的問題 

查閱資料得知, 

當contentType設置為三個常用的格式以外的格式,如“application/json”時,會先發送一個試探的OPTIONS類型的請求給服務端。在這時,單純的在業務接口response添加Access-Control-Allow-Origin 由於還沒有走到所以不會起作用。

解決方案: 
在服務端增加一個攔截器 
用於處理所有請求並加上允許跨域的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class CommonInterceptor implements HandlerInterceptor {
 
 
     private List< String > excludedUrls;
 
     public List< String > getExcludedUrls() {
         return excludedUrls;
     }
 
     public void setExcludedUrls(List< String > excludedUrls) {
         this.excludedUrls = excludedUrls;
     }
 
     /**
      *
      * 在業務處理器處理請求之前被調用 如果返回false
      * 從當前的攔截器往回執行所有攔截器的afterCompletion(),
      * 再退出攔截器鏈, 如果返回true 執行下一個攔截器,
      * 直到所有的攔截器都執行完畢 再執行被攔截的Controller
      * 然后進入攔截器鏈,
      * 從最后一個攔截器往回執行所有的postHandle()
      * 接着再從最后一個攔截器往回執行所有的afterCompletion()
      *
      * @param  request
      *
      * @param  response
      */
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                              Object handler) throws Exception {
         response.setHeader("Access-Control-Allow-Origin", "*");
         response.setHeader("Access-Control-Allow-Methods", "*");
         response.setHeader("Access-Control-Max-Age", "3600");
         response.setHeader("Access-Control-Allow-Headers",
                 "Origin, X-Requested-With, Content-Type, Accept");
         return true;
     }
 
     // 在業務處理器處理請求執行完成后,生成視圖之前執行的動作
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            ModelAndView modelAndView) throws Exception {
 
     }
 
     /**
      *
      * 在DispatcherServlet完全處理完請求后被調用
      * 當有攔截器拋出異常時,
      * 會從當前攔截器往回執行所有的攔截器的afterCompletion()
      *
      * @param request
      *
      * @param response
      *
      * @param handler
      *
      */
     public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                 Object handler, Exception ex) throws Exception {
 
     }
}

spring resultful無法像在jsp提交表單一樣處理數據必須加上@RequestBody,可以直接json轉換object,但是對與沒有bean的表單數據,建議轉換為map對象,類似@RequestBody Map

原文章鏈接:https://www.cnblogs.com/zr123/p/8178817.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM