vue脚手架中vue-resource发送ajax请求

mac2024-03-10  25

1.首先先下载    vue-resource  

  npm install vue-resource    or    yarn add resource  前提是你的电脑装了 yarn  没有的话  npm -g install yarn

2.在脚手架的main.js中注册

注意下  axios是用原型对象注册的  vue-resource是 vue.use()注册 因为axios是第三方插件库  vue.resource是vue自己的

3.第三步发送ajax

我是以这三种方法进行发送的 我一个一个进行讲解,当你注册完了之后可以直接子组件中使用 用 this.$http进行使用

1.发送jsonp请求  我是请求的一个360的接口  是返回的一个搜索提醒的ajax公共接口

2.发送get请求  get请求和jsonp请求有点类似  除了名称不同 其他基本相同

3.发送post请求  post请求有点特殊  你得带上   {emulateJSON:true} 这句话才行 否则 参数就穿不过去  相当于 原生ajax的那句

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") 没有这句话 参数传不过去

4.进行测试

最后打开控制台发送请求数据都回来了   我用的是node.js的服务器,后台代码我在这里也展示下  但不详细讲解了

var express=require("express"); var bodyParser=require("body-parser"); var cors=require("cors"); var app=new express(); // 创建application/x-www-from-urlencoded app.use(bodyParser.urlencoded({extended:false}));//解析 x-www-form-urlencoded //支持ajax跨域请求 app.use(cors({     "Access-Control-Allow-Origin":"*" })) app.listen(5050);

app.get("/",(req,res)=>{     //在每一次响应头这里添加ajax跨域请求     //res.header("Access-Control-Allow-Origin","*");     var type;     if(req.query.type!=undefined){         type=req.query.type;     }     if(type=="a"){         setTimeout(function(){             res.send({type:"a",count:30})         },3000);     }else if(type=="b"){         setTimeout(function(){             res.send({type:"b",count:40})         },3000);     }else if(type=="c"){         setTimeout(function(){             res.send({type:"c",count:50})         },3000);     }else{         res.send("这次的请求没有带参数!");     } }) app.post("/",(req,res)=>{     console.log("有人进来了");         //res.header("Access-Control-Allow-Origin","*");     console.log(req.body.type);     console.log(11);     var type=req.body.type;     if(type=="a"){         setTimeout(function(){             res.send({type:"a",count:30})         },3000);     }     if(type=="b"){         setTimeout(function(){             res.send({type:"b",count:40})         },3000);     }     if(type=="c"){         setTimeout(function(){             res.send({type:"c",count:50})         },3000);     } })

最新回复(0)