Ajax请求

1>解决跨域问题

1.1前端解决。只需要在vue.config.js中增加devServer节点增加代理:

const path = require("path");
const resolve = dir => path.join(__dirname, dir);
const BASE_URL = process.env.NODE_ENV === 'procution' ? '/iview-admin/' : '/'
module.exports = {
lintOnSave: false,
baseUrl: BASE_URL,
chainWebpack: config => {
config.resolve.alias.set("@",resolve('src')).set("_c",resolve('src/components'))
},
//打包时不生成.map文件
productionSourceMap: false,
//跨域配置
devServer: {
proxy:"http://localhost:4000"

}

}

1.2后端解决,应用cors(Cross-Origin Resource Sharing)解决。

如果是node环境,可以这样写:

app.all("*",(req,res,next)=>{
res.hearder("Access-Control-Allow-Origin","*");
res.hearder("Access-Control-Allow-Headers","X-Requested-With,Content-Type");
res.hearder("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
});

如果是.net环境,在Global.asax中添加如下代码片段:

protected void Application_BeginRequest(object sender, EventArgs e)
{
  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
  if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
  {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "");
    HttpContext.Current.Response.End();
  }
}

2>封装axios

下面用axios模拟一个ajax请求为例来对其进行封装:

后端采用node.js模拟一个接口,代码如下:

router.post('getUSerInfo', function(req, res, next) {
console.log('请求成功');
res.status(200).send({
code: 200,
data: {
name: "Lison"
}
});
});

前端代码目录结构:

config/index.js:

export const baseURL =
process.env.NODE_ENV == "production"
? "http://production.com"
: "http://localhost:3000";

lib/axios.js:

import axios from "axios";
import { baseURL } from "@/config";
//ES6类的写法
class HttpRequest {
//ES6默认参数
constructor(baseUrl = baseURL) {
this.baseUrl = baseUrl;
this.queue = {}; //将请求都放到队列中
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
hearders: {
//
}
};
return config;
}
//封装拦截器
interceptors(instance, url) {
instance.interceptors.request.use(
config => {
//添加全局的loading
//Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组
if (!Object.keys(this.queue).length) {
//spin.show
}
this.queue[url] = true;
return config;
},
error => {
return Promise.reject(error);
}
);
instance.interceptors.response.use(
res => {
delete this.queue[url];
const { data, status } = res;
return { data, status };
},
error => {
delete this.queue[url];
return Promise.reject(error);
}
);
} request(options) {
debugger
const instance = axios.create();
/**
* Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
* const target = { a: 1, b: 2 };
* const source = { b: 4, c: 5 };
* const returnedTarget = Object.assign(target, source);
* console.log(target);
* expected output: Object { a: 1, b: 4, c: 5 }
*/
options = Object.assign(this.getInsideConfig(), options);
this.interceptors(instance, options.url);
return instance(options);
}
} export default HttpRequest;

api/index.js

import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios

api/user.js

import axios from "./index";

export const getUserInfo = ({ userId }) => {
debugger
return axios.request({
url: "/getUserInfo",
method: "post",
data: {
userId
}
});
};

home.vue:

  <template>
<div class="home">
<b>{{ food }}</b>
<button @click="getInfo">请求数据</button>
</div>
</template> <script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
import { getUserInfo } from '@/api/user'
export default {
name: "home",
components: {
HelloWorld
},
props: {
food: {
type: String,
default: "apple"
}
},
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
next(vm => {
//若想使用实例,可使用这种方法
console.log(vm);
});
},
beforeRouteLeave(to, from, next) {
// const leave = confirm('您确定要离开吗?')
// if (leave) next()
// else next(false)
next();
},
methods: {
getInfo() {
getUserInfo({ userId:
21 }).then(res => {
console.log("res: "
, res);
});
}

}
};
</script>

Vue处理ajax请求的更多相关文章

  1. 从零开始学 Web 之 Vue.js(四)Vue的Ajax请求和跨域

    大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...

  2. vue 发送ajax请求

    一. 简介 1.vue本身不支持发送AJAX请求,需要使用vue-resource(vue1.0版本).axios(vue2.0版本)等插件实现 2.axios是一个基于Promise的HTTP请求客 ...

  3. vue发送ajax请求

    一.vue-resource 1.简介 一款vue插件,用于处理ajax请求,vue1.x时广泛应用,现不被维护. 2.使用流程 step1:安装 [命令行输入] npm install vue-re ...

  4. vue实现ajax请求(vue-resource和axios)

    1.vue-resouce实现ajax请求 vue1中主要用vue-resouce实现ajax请求, 2.1 引用vue-resouce 引入axios,直接在index.html文件中引入; 或者在 ...

  5. vue中ajax请求发送

    示例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8& ...

  6. vue的ajax请求之axios

    axios.get(this.apiUrl+'good/info',{params:{'goodsid':'sp441153'}}) .then(function(response){ console ...

  7. vue实现ajax滚动下拉加载,同时具有loading效果

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  8. Vue框架axios请求(类似于ajax请求)

    Vue框架axios get请求(类似于ajax请求) 首先介绍下,这个axios请求最明显的地方,通过这个请求进行提交的时候页面不会刷新 <!DOCTYPE html> <html ...

  9. Vue(七)发送Ajax请求

    发送AJAX请求 1. 简介 vue本身不支持发送AJAX请求,需要使用vue-resource.axios等插件实现 axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue ...

随机推荐

  1. (function (window, document, undefined) {})(window, document)什么意思?

    1.IIFE(即时调用的函数表达式),它采取以下表达式: (function (window, document, undefined) { // })(window, document); Java ...

  2. ue4 character 物理测试

    charactor里 CapsuleComponnet Mesh CharacterMovement 3个组件里有有物理开关 目前看Mesh的Simulate Physics+Enable Gravi ...

  3. [UE4]C++设置AnimInstance的相关问题

    注意:ue4 4.17调用LoadObject<UAnimBlueprintGeneratedClass>直接崩 http://aigo.iteye.com/blog/2285001 UA ...

  4. MySQL下载与安装配置

    一.Windows 上安装 MySQL Windows 上安装 MySQL 相对简单,最新版本下载地址: 官网:https://dev.mysql.com/downloads/mysql/ 下载步骤: ...

  5. Python学习笔记(数据处理)

    处理文件中数据 (统计分数) 看一下我们的文档里的数据: #-- scores.txt 刘备 23 35 44 47 51 关羽 60 77 68 张飞 97 99 89 91 诸葛亮 100 1.先 ...

  6. Spring JdbcTemplate详解及项目中的运用

    1.Spring对不同的持久化支持: Spring为各种支持的持久化技术,都提供了简单操作的模板和回调 ORM持久化技术 模板类 JDBC org.springframework.jdbc.core. ...

  7. nginx 第二课

    基本配置格式 Nginx全局配置参数 使用include文件 HTTP的server部分 虚拟服务器部分 location —— where,when,how. mail的server部分. 完整的示 ...

  8. 黑马旅游网案例 Bug集锦

  9. Java 基础类库

    与用户互动 1. 运行java程序的参数 public static void main(Stirng[] args) 这个方法是有JVM调用,因此用public static修饰,并且没有返回值,同 ...

  10. Python web前端 11 form 和 ajax

    Python web前端 11 form 和 ajax 一.打开服务器 将handlers.py.httpd.py和libs.py三个文件放入新文件夹中,双击打开httpd.py文件即可 二.ajax ...