-
axios
2019-11-30 15:25:21axios1 搭建RESTful接口
json-server:https://github.com/typicode/json-server
npm install -g json-server
- posts:文章
- comments:评论
- profile:作者
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }
json-server --watch db.json
2 测试axios
<div> <button onclick="testGet()">GET请求</button> <button onclick="testPost()">POST请求</button> <button onclick="testPut()">PUT请求</button> <button onclick="testDelete()">DELETE请求</button> </div> <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
/* 1. GET请求: 从服务器端获取数据*/ function testGet() { // axios.get('http://localhost:3000/posts') // axios.get('http://localhost:3000/posts/1') axios.get('http://localhost:3000/posts?id=1') .then(response => { console.log('/posts get', response.data) }) }
/* 2. POST请求: 向服务器端添加新数据*/ function testPost() { axios.post('http://localhost:3000/posts', {"title": "json-server2", "author": "typicode2"}) .then(response => { console.log('/posts post', response.data) }) }
/* 3. PUT请求: 更新服务器端已经数据 */ function testPut() { axios.put('http://localhost:3000/posts/2', {"title": "json-server...", "author": "typicode..."}) .then(response => { console.log('/posts put', response.data) }) }
/* 4. DELETE请求: 删除服务器端数据 */ function testDelete() { axios.delete('http://localhost:3000/posts/2') .then(response => { console.log('/posts delete', response.data) }) }
-
Axios
2019-08-01 16:38:36Axios简介 Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,用来发送 HTTP 请求,其作用类似于jQuery 的 ajax() 方法。 Axios 支持如下特性: 从浏览器中创建 XMLHttpRequests 从 node.js ...Axios简介
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中,用来发送 HTTP 请求,其作用类似于jQuery 的 ajax() 方法。
Axios 支持如下特性:
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
安装
直接引用
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Npm安装
npm install axios --save
API
axios(config)
该方法允许通过向 axios 传递一个JSON配置来创建请求。下面列举出了创建请求时可以用的配置选项。其中只有 url 是必需的。如果没有指定 method,请求将默认使用 get方法。
{ // `url` 是用于请求的服务器 URL url: '/user', // `method` 是创建请求时使用的方法 method: 'get', // default // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。 // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data, headers) { // 对 data 进行任意转换处理 return data; }], // `transformResponse` 在传递给 then/catch 前,允许修改响应数据 transformResponse: [function (data) { // 对 data 进行任意转换处理 return data; }], // `headers` 是即将被发送的自定义请求头 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即将与请求一起发送的 URL 参数 // 必须是一个无格式对象(plain object)或 URLSearchParams 对象 params: { ID: 12345 }, // `paramsSerializer` 是一个负责 `params` 序列化的函数 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` 是作为请求主体被发送的数据 // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH' // 在没有设置 `transformRequest` 时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 浏览器专属:FormData, File, Blob // - Node 专属: Stream data: { firstName: 'Fred' }, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 `timeout` 的时间,请求将被中断 timeout: 1000, // `withCredentials` 表示跨域请求时是否需要使用凭证 withCredentials: false, // default // `adapter` 允许自定义处理请求,以使测试更轻松 // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示应该使用 HTTP 基础验证,并提供凭据 // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` 允许为上传处理进度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` 允许为下载处理进度事件 onDownloadProgress: function (progressEvent) { // 对原生进度事件的处理 }, // `maxContentLength` 定义允许的响应内容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目 // 如果设置为0,将不会 follow 任何重定向 maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项: // `keepAlive` 默认没有启用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定义代理服务器的主机名称和端口 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用于取消请求的 cancel token // (查看后面的 Cancellation 这节了解更多) cancelToken: new CancelToken(function (cancel) { }) }
请求返回的响应内容结构如下:
{ // `data` 由服务器提供的响应 data: {}, // `status` 来自服务器响应的 HTTP 状态码 status: 200, // `statusText` 来自服务器响应的 HTTP 状态信息 statusText: 'OK', // `headers` 服务器响应的头 headers: {}, // `config` 是为请求提供的配置信息 config: {}, // 'request' // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} }
请求示例:
// 发送 GET 请求(默认的方法) axios('/user/89757'); // 发送 GET 请求,获取json数据 axios("http://localhost:8080/package.json").then(res => { console.log(res.data) }).catch(error => { console.log("请求错误:" + error) }); // 发送 GET 请求,获取图片 axios({ url: "http://localhost:8080/logo.png", method: "get", responseType: 'stream' }).then(res => { res.data.pipe(fs.createWriteStream('vue.png')) }); // 发送 POST 请求 axios({ url: "http://localhost:8080/user/89757/update", method: "post", data: { name: "graython", salary: 5000 } }).then(res => { console.log(res.data) });
方法别名
为了方便调用,Axios为所有支持的请求方法提供了别名,分别对应八种请求类型。在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.options(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
请求示例:
axios.post("http://localhost:8080/user/89757/update", { name: "graython", salary: 5000 },{ headers: { token: "pengjunlee"} }).then(res => { console.log(res.data) });
并发
Axios 还额外提供了两个用来处理并发请求的助手函数:
- axios.all(iterable)
- axios.spread(callback)
请求示例:
</header> <script type="text/javascript"> // 发送 GET 请求,获取用户基本信息 function getUserInfos() { return axios.get("http://localhost:8080/user/89757/infos"); }; // 发送 GET 请求,获取用户权限信息 function getUserPerms() { return axios.get("http://localhost:8080/user/89757/perms"); }; </script> </header>
用户登录前同时获取用户基本信息和用户权限信息进行处理。
beforeUserLogin: function () { axios.all([ getUserInfos(), getUserPerms() ]).then(axios.spread(function (infos, perms) { // 此处可以对获取到的用户基本信息和用户权限信息进行处理 console.log(infos.data); console.log(perms.data); })) }
创建实例
你也可以把常用的配置新建一个 axios 实例,然后调用自定义的 axios 实例去发送请求。
请求示例:
const instance = axios.create({ baseURL: 'http://localhost:8080/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); // 发送get请求,获取json数据 instance("package.json").then(res => { console.log(res.data) }).catch(error => { console.log("请求错误:" + error) });
拦截器
利用拦截器你可以在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); });
如果你想在稍后移除拦截器,可以这样:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
错误处理
axios.get('/user/89757') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
参考文章
-
Vue之Axios跨域问题解决方案
2019-02-19 14:32:31背景:因为axios中只能使用get和post方法来进行请求数据,没有提供jsonp等方法进行跨域访问数据 axios中文网址:https://www.kancloud.cn/yunye/axios/234845 // axios 中的GET请求 axios.get('/user', { ...背景:因为axios中只能使用get和post方法来进行请求数据,没有提供jsonp等方法进行跨域访问数据
axios中文网址:https://www.kancloud.cn/yunye/axios/234845
// axios 中的GET请求 axios.get('/user', { params: { ID: ‘001’ } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // axios 中的POST请求 axios.post('/user', { firstName: '1', lastName: '2' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
方案1:既然使用axios直接进行跨域访问不可行,我们就需要配置代理了。代理可以解决的原因:因为客户端请求服务端的数据是存在跨域问题的,而服务器和服务器之间可以相互请求数据,是没有跨域的概念(如果服务器没有设置禁止跨域的权限问题),也就是说,我们可以配置一个代理的服务器可以请求另一个服务器中的数据,然后把请求出来的数据返回到我们的代理服务器中,代理服务器再返回数据给我们的客户端,这样我们就可以实现跨域访问数据。
准备工作:安装所需中间件和插件等,比如axios,http-proxy-middleware等。
具体案例:这里以访问豆瓣Top250为例,直接访问如下:
axios.get("http://api.douban.com/v2/movie/top250") .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) })
当执行npm run dev时,控制台报错如下:
事实证明直接请求确实出现跨域问题了,下面具体演示解决跨域问题的步骤:
上面所说的必备条件都已安装完成的情况下,执行以下步骤即可解决问题:
1.配置BaseUrl
在main.js中,配置数据所在服务器的前缀(即固定部分),代码如下:
// 项目入口,配置全局vue import Vue from 'vue' import VueRouter from './router/routes.js' import Store from './store/index.js' import './assets/less/index.less' import App from './App.vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-default/index.css' import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = '/api' //关键代码 Vue.config.productionTip = false Vue.use(ElementUI); new Vue({ router:VueRouter, store:Store, template:'<App/>', components: {App} }).$mount('#app') // 默认进入商品模块 // VueRouter.push({ path: '/home' })
关键代码:axios.defaults.baseURL = '/api',作用是我们每次发送的请求都会带一个/api的前缀。
2.配置代理
在config文件夹下的index.js文件中的proxyTable字段中,作如下处理:
dev: { env: require('./dev.env'), port: 8090, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target:'http://api.douban.com/v2', // 你请求的第三方接口 changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题 pathRewrite:{ // 路径重写, '^/api': '' // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。 } } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false }
3.在具体使用axios的地方,修改url如下即可:
axios.get("/movie/top250").then((res) => { res = res.data if (res.errno === ERR_OK) { this.themeList=res.data; } }).catch((error) => { console.warn(error) })
4.重新启动项目之后,已经解决了跨域问题,结果如下:
原理:
因为我们给url加上了前缀/api,我们访问/movie/top250就当于访问了:localhost:8080/api/movie/top250(其中localhost:8080是默认的IP和端口)。
在index.js中的proxyTable中拦截了/api,并把/api及其前面的所有替换成了target中的内容,因此实际访问Url是http://api.douban.com/v2/movie/top250。
至此,纯前端配置代理解决axios跨域得到解决。
方案2:后端处理跨域问题,加个过滤器即可解决,如下:
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 跨域过滤器 * @author jitwxs * @since 2018/10/16 20:53 */ public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; // 不使用*,自动适配跨域域名,避免携带Cookie时失效 String origin = request.getHeader("Origin"); if(StringUtils.isNotBlank(origin)) { response.setHeader("Access-Control-Allow-Origin", origin); } // 自适应所有自定义头 String headers = request.getHeader("Access-Control-Request-Headers"); if(StringUtils.isNotBlank(headers)) { response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", headers); } // 允许跨域的请求方法类型 response.setHeader("Access-Control-Allow-Methods", "*"); // 预检命令(OPTIONS)缓存时间,单位:秒 response.setHeader("Access-Control-Max-Age", "3600"); // 明确许可客户端发送Cookie,不允许删除字段即可 response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } /* 注册过滤器: @Bean public FilterRegistrationBean registerFilter() { FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(); bean.addUrlPatterns("/*"); bean.setFilter(new CorsFilter()); // 过滤顺序,从小到大依次过滤 bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; } */ }
以上axios解决跨域的方案,希望能解决大家遇到的跨域问题,如有问题请添加评论。
-------------------------------------------------------------------------分割线-------------------------------------------------------------------------------------
根据评论区内容,区分一下生产环境和开发环境,集体配置如下:
1.在config文件夹里面创建一个api.config.js的配置文件
const isPro = Object.is(process.env.NODE_ENV, 'production') console.log(isPro); module.exports = { baseUrl: isPro ? 'https://www.***/index.php/Official(线上地址)' : 'api/' }
2.在main.js文件里面引入上面文件,这样就可以保证动态的匹配生产和开发环境的定义前缀了,代码如下:
import Vue from 'vue' import App from './App' import router from './router' import 'bootstrap/dist/js/bootstrap.min' import 'bootstrap/dist/css/bootstrap.min.css' import axios from 'axios' import apiConfig from '../config/api.config' Vue.prototype.$axios = axios; Vue.config.productionTip = false; axios.defaults.baseURL = apiConfig.baseUrl;// 配置接口地址 axios.defaults.withCredentials = false;
以上两步即可解决vue的跨域问题,并且可以可以直接build打包到线上,如有问题,请评论区留言,希望对你有所帮助。
-
vue-axios的使用及其get与post网络请求
2018-06-23 02:39:20一、vue-axios学习网址 网址1: https://github.com/imcvampire/vue-axios 网址2: https://www.npmjs.com/packge/axios 二、vue中get与post请求 vue高版本中,推荐使用axios进行网络请求,而不再使用vue-...一、vue-axios学习网址
网址1: https://github.com/imcvampire/vue-axios
网址2: https://www.npmjs.com/packge/axios
二、vue中get与post请求
vue高版本中,推荐使用axios进行网络请求,而不再使用vue-resource。
在vue04项目中,在终端运行 npm install --save axios vue-axios ,下载vue-axios插件
注意:“vue04项目”是指我的上篇博客中通过vue-cli脚手架创建的项目(后面我会附上源码,博客标题:《利用vue-cli创建项目步骤简述》,博客链接:https://blog.csdn.net/qq_41115965/article/details/80766520)提示:使用插件的时候,一般都要在入口文件main.js中引入,因为main.js项目运行首先运行的文件。具体代码如下:
main.js文件
import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios)
疑问:为什么使用Vue.use(VueAxios, axios)
解惑:通过全局方法 Vue.use() 使用插件,就相当于调用install方法,vue官网举例如下:
// 调用 `MyPlugin.install(Vue)` Vue.use(MyPlugin)
注意:在comunication组件中发起请求,要使用Vue,所以需要引入,即import vue from 'vue'(comunication组件是本例中发起网络请求的组件)
axios的get请求的参数解释:
第一个参数是链接,参数还可以拼接,也可以使用params形式。学习网址: https://www.npmjs.com/package/axios
axios的get使用方法(源自相关学习网址截图)
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
注意:原本url应该http://127.0.0.1:5888/api/get,但是开发时,代码都是放在公司服务器上的,绝对不会存在跨域问题。测试环节中,没有必要让后台进行jsonp处理或者cors。
此时点击comunication组件中的按钮,发起get请求,会出现报错。报错信息为:GET http://localhost:8080/api/get?name=%E5%AC%B4%E6%94%BF&age=45 404 (Not Found)
报错解释:
其中http://localhost:8081是默认的服务器端口,在package.json中 "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",利用webpack-dev-server插件,搭建一个服务器,执行webpack.dev.conf.js,内置的服务器没有/get/api接口,所以会报错。
解决方法:设置转发的域具体做法:查看package.json文件,"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",双击打开build/webpack.dev.conf.js文件,找到proxy设置代理,按住Ctrl并鼠标点击proxy: config.dev.proxyTable,此时会进入index.js文件,配置转发的域,具体做法见下图,而后在终端按下Ctrl+c,而后 npm start 重启项目。
点击get请求button,请求成功的标志,见下图:
comunication.vue组件中的get请求代码
// 发起get请求 Vue.axios.get('/api/get', { // get传递的query参数(传递的参数应与后台人员协商,本次模拟不做限制,不做判断) params: { name: '嬴政', age: 45 } }).then((response) => { // then 指成功之后的回调 (注意:使用箭头函数,可以不考虑this指向) console.log(response); console.log(response.data); this.resData = response.data; }).catch((error) => { // catch 指请求出错的处理 console.log(error); });
axios的post请求方法介绍
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
点击post请求button,请求成功的标志,见下图:
comunication.vue组件中的post请求代码
// 提示:该方式传递的参数是json格式,如上传不成功,需检查后台接收的方式是不是application/x-www-form-urlencoded默认格式,jquery中ajax请求的就是application/x-www-form-urlencoded,后台需要body-parser解码 Vue.axios.post('/api/post', { // 此参数就是写到请求体中的参数 stuName: '盖聂', height: 180 }).then((response) => { console.log(response); console.log(response.data); this.postData = response.data; }).catch((error) => { console.log(error); });
服务器端server.js文件
附加练习:引入body-parser访问body
做法:因为node-modules中依赖已经包含了body-parser,直接使用即可。根据post请求传入参数的形式,阅读body-parser的readme文件,选择合适的使用方式。代码修改:在server.js文件中添加以下代码
var bodyParser = require('body-parser'); app.use(bodyParser.json());
三、示例代码
comunication.vue
<template> <div id="comunication"> <h3>comunication组件--通信组件</h3> <button @click="doGet">GET请求</button> <br> <span class="getData">get请求到的数据:{{resData}}</span> <button @click="doPost">POST请求</button> <br> <span class="postData">post请求到的数据:{{postData}}</span> <h4>vue-axios网络请求演示参考网站</h4> <a href="https://github.com/imcvampire/vue-axios">https://github.com/imcvampire/vue-axios</a> <a href="https://www.npmjs.com/package/axios">https://www.npmjs.com/package/axios</a> <form action="" enctype="application/x-www-form-urlencoded"></form> </div> </template> <script> // 需要使用Vue,所以需要引入 import Vue from 'vue' export default { data (){ return { resData:[], postData:[] } }, // vue高版本中,推荐使用axios进行网络请求,而不再使用vue-resource methods: { doGet(){ // 发起get请求 Vue.axios.get('/api/get', { // get传递的query参数(传递的参数应与后台人员协商,本次模拟不做限制,不做判断) params: { name: '嬴政', age: 45 } }).then((response) => { // then 指成功之后的回调 (注意:使用箭头函数,可以不考虑this指向) console.log(response); console.log(response.data); this.resData = response.data; }).catch((error) => { // catch 指请求出错的处理 console.log(error); }); }, doPost(){ // 提示:该方式传递的参数是json格式,如上传不成功,需检查后台接收的方式是不是application/x-www-form-urlencoded默认格式,jquery中ajax请求的就是application/x-www-form-urlencoded,后台需要body-parser解码 Vue.axios.post('/api/post', { // 此参数就是写到请求体中的参数 stuName: '盖聂', height: 180 }).then((response) => { console.log(response); console.log(response.data); this.postData = response.data; }).catch((error) => { console.log(error); }); } } } </script> <style scoped> #comunication { border: 1px solid gold; padding: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; margin-bottom: 10px; } h3 { width: 100%; height: 60px; line-height: 60px; text-align: center; background: gainsboro; font-size: 30px; } button { background-color: #008CBA; padding: 10px 20px; border: none; font-size: 18px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; display: block; } button:hover { background-color: #008CDA; color: #ffffff; } h4 { font-size: 24px; } a { background: rgba(255, 255, 0, 0.5); padding: 5px 20px; width: 350px; border-radius: 8px; text-decoration: none; } .getData,.postData{ font-size: 20px; background: greenyellow;padding: 5px 10px 5px 20px; border-radius:18px; display: block; margin-bottom: 20px; margin-top: 10px; width: 900px; } </style>
main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios); Vue.config.productionTip = false; /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>', data(){ return { totalVm: new Vue() } } })
index.js
'use strict' // Template version: 1.3.1 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { // 配置转发的域 /api下面的请求均发起转发 '/api':{ target:'http://127.0.0.1:5888', changeOrigin:true } }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
以下为示例涉及的其他代码(与博客介绍的内容关系不大,主要复习组件间的通信,为防止运行错误,现附上代码)
test.vue
<template> <div id="test"> <h3>test组件--演示组件传值与方法调用</h3> <button @click="doClick()">点击按钮,向根组件传值</button> <p class="childToParent">app组件传过来的值:{{cn}}<span class="tip">提示:父向子传值</span></p> <table border="1" cellspacing="0" width="250"> <tr> <th>ID</th> <th>姓名</th> <th>身高</th> </tr> <tr v-for="girl in arr" :key="girl.ID"> <td>{{girl.ID}}</td> <td>{{girl.name}}</td> <td>{{girl.height}}</td> </tr> </table> </div> </template> <script> export default { name: 'test', props: { cn: { type: String } }, data(){ return { msg: 'hello world', arr: [] } }, created(){ this.$root.totalVm.$on('custom', (v) => { this.arr = v; }) }, methods: { doClick(){ console.log('您点击了按钮。。。'); this.$emit('event1', this.msg); } } } </script> <style scoped> #test { border: 3px solid green; border-radius: 8px; padding: 10px; margin-bottom: 10px; } h3 { width: 100%; height: 60px; line-height: 60px; text-align: center; background: gainsboro; font-size: 30px; } button { background-color: #008CBA; padding: 10px 20px; border: none; font-size: 18px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } button:hover { background-color: #008CDA; color: #ffffff; } tr { text-align: center; font-size: 16px; } .childToParent { font-size: 24px; } .tip { background: red; font-size: 16px; padding: 5px 10px; border: 1px solid transparent; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin-left: 20px; } </style>
test02.vue
<template> <div id="test02"> <h3>test02组件--演示组件传值与方法调用</h3> <button @click="doClick">向test组件发送消息,生成动态表格填充数据</button> <span class="tip">提示:兄弟组件通信</span> </div> </template> <script> export default { data(){ return { aGirls: [{ name: '韩非', height: 180, ID: 1002 }, { name: '李斯', height: 182, ID: 1003 }, { name: '卫庄', height: 183, ID: 1004 }, { name: '嬴政', height: 183, ID: 1005 } ] } }, methods: { doClick(){ this.$root.totalVm.$emit('custom', this.aGirls) } } } </script> <style scoped> #test02 { border: 2px solid blue; padding: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; margin-bottom: 10px; } h3 { width: 100%; height: 60px; line-height: 60px; text-align: center; background: gainsboro; font-size: 30px; } button { background-color: #008CBA; padding: 10px 20px; border: none; font-size: 18px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } button:hover { background-color: #008CDA; color: #ffffff; } .tip { background: red; font-size: 16px; padding: 5px 10px; border: 1px solid transparent; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin-left: 20px; } </style>
app.vue
<template> <div id="app"> <h3>app组件--根组件</h3> <p class="testToApp">test组件传过来的值为:{{szStr}}<span class="tip">提示:子向父传值</span></p> <!--必须引入才可以显示子组件的内容--> <my-test @event1="getInfo($event)" :cn="carName"></my-test> <my-test02></my-test02> <my-comunication></my-comunication> </div> </template> <script> // 引入 import myTest from './components/test.vue'; import myTest02 from './components/test02.vue' import myComunication from './components/comunication/Comunication.vue' export default { name: 'App', components: { myTest, myTest02, myComunication }, data(){ return { szStr: '', carName: 'BWM' } }, methods: { getInfo(e){ this.szStr = e; } } } </script> <style scoped> #app { border: 3px dashed #d17bff; padding: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; } h3{ width: 100%; height: 60px; line-height: 60px; text-align: center; background: gainsboro; font-size: 30px; } .testToApp{ font-size: 24px; } .tip { background: red; font-size: 16px; padding: 5px 10px; border: 1px solid transparent; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin-left: 20px; } </style>
四、效果图
温馨提示
更多博文,请关注公众号:xssy5431(小拾岁月)
扫码:
-
axios的使用
2019-06-10 23:14:46首先要在项目目录下使用如下命令下载axios $npm i axios -S 而后在src目录下创建requests文件夹,里面用来存放你整个项目的ajax请求。 此文件夹中首先创建一个index.js文件 编写里面的内容: //引入axios import ... -
Axios由浅入深
2020-02-21 13:00:011. 什么是axios axios是通过promise实现对ajax技术的一种封装,就像jQuery实现ajax封装一样。 简单来说: ajax技术实现了网页的局部数据刷新,axios实现了对ajax的封装,可以用于浏览器和node.js。axios是ajax, ... -
axios安装 使用及如何解决‘axios is not defined’
2019-05-31 11:31:30安装axios 1、使用npm $ npm install axios 2、使用 bower: $ bower install axios 3、使用 cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 我用的npm,说说我在... -
axios安装包
2019-02-19 16:20:48前端技术axios,从浏览器中创建 XMLHttpRequest,支持 Promise API。客户端支持防止 CSRF/XSRF -
关于vue使用axios post发送json数据跨域请求403的解决方法
2018-08-17 15:31:49最近使用vue框架开发项目的时候, 遇到了一个问题,其实这个问题在之前就已经遇到过,不过因为当时没有时间,所以采用了另外一...vue开发的时候,使用axios跨域发送请求,同时post发送的数据格式是json格式,发送出... -
axios和vue-axios区别及vue-axios使用
2019-10-21 19:17:46一、axios和vue-axios区别 1、axios是基于promise的HTTP库,可以使用在浏览器和node.js中,它不是vue的第三方插件 2、使用的时候不能像vue的插件(如:Vue-Router、VueX等)通过Vue.use()安装插件,需要在原型上进行... -
细谈 axios和ajax区别
2019-03-11 18:00:53刚刚接触axios有好多疑惑。它和ajax有什么关系呢和区别呢?接下来一起看下: 1.区别 axios是通过promise实现对ajax技术的一种封装,就像jQuery实现ajax封装一样。 简单来说: ajax技术实现了网页的局部数据刷新,... -
axios总结
2020-09-08 23:59:05axios: 1.作用: 1)ajax工具包 2)promise 3)支持请求和响应的拦截 nodejs和网页端都可以使用 2.使用 : 1.安装 npm install axios 2.导入挂载 import axios from ‘axios’ Vue.prototype $http=axios 3.在组件... -
vue axios 封装 全局调用axios
2020-03-10 20:10:051.简单的封装了一下Axios 有其他的需求各位在自己拓展一下 import axios from "axios" import qs from "qs" axios.defaults.timeout=3000 //响应时间 axios.defaults.headers.post['Content-Type'] = 'application...
-
备战2021软考网络规划设计师顺利通关培训套餐
-
S7-200常用问题.rar
-
【数据分析-随到随学】量化交易策略模型
-
2021-01-20
-
flutter插件调用APP页面、使用原生aar,framework库
-
解决gazebo中urdf模型显示不正常的问题,rviz中显示模型
-
bootstrap-4.0.0.zip
-
设计一控制系统并仿真:
-
最新版windows mysql-8.0.23-winx64.zip
-
中技学生期末评语
-
【2021】Python3+Selenium3自动化测试(不含框架)
-
神经网络激活函数优缺点和比较(sigmod,tanh,relu,softmax,leaky relu,ELU,SELU)
-
rocketmq-console-ng-2.0.0.jar
-
Qt操作XML文档(增删改查)
-
树莓派上python和C语言编程
-
蓝桥杯第九天
-
专利预警与技术创新(PDF)
-
单片机完全学习课程全五季套餐
-
SetunaConfig.xml
-
Selenium3分布式与虚拟化