温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue 中怎么请求后台数据

发布时间:2021-07-09 11:57:08 来源:亿速云 阅读:140 作者:Leah 栏目:web开发

这篇文章给大家介绍vue 中怎么请求后台数据,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

在入口函数中加入

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

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

提交表单

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

解决方案:

在服务端增加一个拦截器

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

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、

关于vue 中怎么请求后台数据就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI