Title

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
posted @ 2021-10-28 19:52  快乐小洋人  阅读(1069)  评论(0编辑  收藏  举报