使用vue-resource实现异步请求发送

7 篇文章 0 订阅
7 篇文章 0 订阅

Vue实现请求发送

vue-resource可以实现getpostjsonp的请求
也可以使用axios的第三方包实现请求发送

  • 导入vue-resource包到项目目录
    • vue-resource依赖于vue,故需先导入vue
  • 使用this.$http.get(url,[options])根据url路径发送get请求
  • 使用this.$http.head(url,[options])
  • 使用this.$http.dalete(url,[options])
  • 使用this.$http.jsonp(url,[options])
  • 使用this.$http.post(url,[body],[options])根据url路径和数据发送post请求
    • 手动发送的post请求默认没有表单格式(application/x-www-form-urlencoded),有的服务器处理不了,通过设置post方法的第三个参数,指定提交内容为普通表单数据格式(application/x-www-form-urlencoded
    • 可以使用emulateJSON指定为true并封装对象传给post方法的第三个参数
  • 使用this.$http.put(url,[body],[options])
  • 使用this.$http.patch(url,[body],[options])
  • 在请求方法上使用.then(successCallback,errorCallback)接收服务器返回的数据并处理
    • successCallback表示成功接收数据的回调函数
    • errorCallback表示接收数据失败之后的回调函数
    • successCallback是必须的,errorCallback是可选的
  • 请求到的数据在result.body
    例如:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./vue.js"></script>
    <script type="text/javascript" src="./vue-resource.js"></script>
</head>
<body>
    <div id="app">
        <input type="button" @click="getInfo" value="发送get请求">
        <input type="button" @click="postInfo" value="发送post请求">
        <input type="button" @click="jsonpInfo" value="发送jsonp请求">
    </div>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                msg:''
            },
            methods: {
                getInfo(){
                    this.$http.get('http://org.practive.ssm/index.html').then((result)=>{
                        console.log(result)
                    })
                },
                postInfo(){
                    this.$http.post('http://org.practive.ssm/OnLinePractice/User/Login',{userEamil : 'w3c@html.com',userPassword : 'adb456'},{}).then((result)=>{
                        console.log(result)
                    })
                },
                jsonpInfo(){
                  this.$http.jsonp('http://org.practive.ssm/OnLinePractice/index3.html').then((result)=>{
                      console.log(result)
                  })
				        }
            }
        });
    </script>
</body>
</html>
  • 遇到的问题:
02.html:1 

Access to XMLHttpRequest at 'http://127.0.0.1/index.html' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

02.html:1 

Uncaught (in promise) Response {url: "http://127.0.0.1/index.html", ok: false, status: 0, statusText: "", headers: Headers, …}body: ""bodyText: ""headers: Headersmap: "": Array(1)0: ""length: 1__proto__: Array(0)concat: ƒ concat()arguments: (...)caller: (...)length: 1name: "concat"__proto__: ƒ ()[[Scopes]]: Scopes[0]constructor: ƒ Array()copyWithin: ƒ copyWithin()entries: ƒ entries()every: ƒ every()fill: ƒ fill()filter: ƒ filter()find: ƒ find()findIndex: ƒ findIndex()flat: ƒ flat()flatMap: ƒ flatMap()forEach: ƒ forEach()includes: ƒ includes()indexOf: ƒ indexOf()join: ƒ join()keys: ƒ keys()lastIndexOf: ƒ lastIndexOf()length: 0map: ƒ map()pop: ƒ pop()push: ƒ push()reduce: ƒ reduce()reduceRight: ƒ reduceRight()reverse: ƒ reverse()shift: ƒ shift()slice: ƒ slice()some: ƒ some()sort: ƒ sort()splice: ƒ splice()toLocaleString: ƒ toLocaleString()toString: ƒ toString()unshift: ƒ unshift()values: ƒ values()Symbol(Symbol.iterator): ƒ values()Symbol(Symbol.unscopables): {copyWithin: true, entries: true, fill: true, find: true, findIndex: true, …}__proto__: Object__proto__: constructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()get __proto__: ƒ __proto__()set __proto__: ƒ __proto__()__proto__: append: ƒ append(name, value)delete: ƒ delete$1(name)deleteAll: ƒ deleteAll()forEach: ƒ forEach(callback, thisArg)get: ƒ (name)getAll: ƒ getAll(name)has: ƒ has(name)set: ƒ (name, value)constructor: ƒ Headers(headers)__proto__: Objectok: falsestatus: 0statusText: ""url: "http://127.0.0.1/index.html"data: (...)__proto__: blob: ƒ blob()json: ƒ json()text: ƒ text()constructor: ƒ Response(body, ref)data: (...)get data: ƒ ()set data: ƒ (body)__proto__: Object
Promise.then (async)
p$1.then @ vue-resource.js:241
getInfo @ 02.html:22
invokeWithErrorHandling @ vue.js:1863
invoker @ vue.js:2188
original._wrapper @ vue.js:7547

vue-resource.js:1088 

XHR failed loading: GET "http://127.0.0.1/index.html".
(anonymous) @ vue-resource.js:1088
PromiseObj @ vue-resource.js:202
xhrClient @ vue-resource.js:1025
sendRequest @ vue-resource.js:1186
Client @ vue-resource.js:1149
Http @ vue-resource.js:1391
Http.(anonymous function) @ vue-resource.js:1422
getInfo @ 02.html:22
invokeWithErrorHandling @ vue.js:1863
invoker @ vue.js:2188
original._wrapper @ vue.js:7547
  • 原因:可能是跨域问题
  • 测试时可以使用nginx排除干扰
    • nginx的更改配置后在windows上的重启命令为nginx -s reload
    • 在使用重启时,需确保nginx已启动
      nginx配置文件nginx.conf中的配置如下:
listen       80;
server_name  org.practive.ssm;
#charset koi8-r;
#access_log  logs/host.access.log  main;
location / {
    #root   html;
  		alias  C:/Users/sh199/Desktop/xc-ui-pc-static-portal/;
  		#alias  C:/Users/sh199/Desktop/s/;
    index  02.html index.htm;
}
  	
  #location / {
    #root   html;
  		#alias  C:/Users/sh199/Desktop/xc-ui-pc-static-portal/;
  		#alias  C:/Users/sh199/Desktop/s/;
    #index  02.html index.htm;
#}
  	
  location /OnLinePractice {
    proxy_pass   http://127.0.0.1:8282;
  		index  index3.html index.htm;
}
  • post提交到后台使用普通表单格式(application/x-www-form-urlencoded),则后端就不需要使用@RequestBody注解接收
  • post提交到后台使用json格式(application/json),则后端就需要使用@RequestBody注解接收

全局配置

全局配置数据接口的根

  • 使用Vue.http.options.root = 'http://org.practice.ssm/'指定为全局的数据请求的域名
    • 在使用异步时url中可以不包含域名且不能在不包含域名的url开头加/

全局配置提交选项

  • 使用Vue.http.options.emulateJSON = true配置post请求的提交选项
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值