栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

vue 请求后台数据的实例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vue 请求后台数据的实例代码

需要引用vue-resource

安装请参考https://github.com/pagekit/vue-resource官方文档

在入口函数中加入

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

在package.json文件中加入

 "dependencies": {
  "vue": "^2.2.6",
  "vue-resource":"^1.2.1"
 },

请求如下

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.

解决办法:在接口中设置

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

2.使用jsonp请求

但是出现如下错误

Uncaught SyntaxError: Unexpected token

查看请求,数据已返回,未解决.

提交表单

 
    
  

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 由于还没有走到所以不会起作用。

解决方案:

在服务端增加一个拦截器

用于处理所有请求并加上允许跨域的头

public class CommonInterceptor implements HandlerInterceptor {

  private List excludedUrls;

  public List getExcludedUrls() {
    return excludedUrls;
  }

  public void setExcludedUrls(List excludedUrls) {
    this.excludedUrls = excludedUrls;
  }

  
  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 {

  }

  
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
  Object handler, Exception ex) throws Exception {

  }
}

spring resultful无法像在jsp提交表单一样处理数据必须加上@RequestBody,可以直接json转换object,但是对与没有bean的表单数据,建议转换为map对象,类似@RequestBody Map、

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/86882.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号