vue使用axios连接数据库

vue使用axios连接数据库vue 连接数据库 vue 中使用 axios1 安装 axiosnpm npminstallax Scdn scriptsrc https unpkg com axios dist axios min js 2 配置 axios 在项目中新建 api index js 文件 用以配置 axiosapi index jsim scriptsrc https

vue连接数据

vue中使用axios

1.安装axios

npm: npm install axios -S cdn:  

2.配置axios

在项目中新建api/index.js文件,用以配置axios

api/index.js

import axios from 'axios'; let http = axios.create({ baseURL: 'http://localhost:8080/', withCredentials: true, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, transformRequest: [function (data) { let newData = ''; for (let k in data) { if (data.hasOwnProperty(k) === true) { newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'; } } return newData; }] }); function apiAxios(method, url, params, response) { http({ method: method, url: url, data: method === 'POST' || method === 'PUT' ? params : null, params: method === 'GET' || method === 'DELETE' ? params : null, }).then(function (res) { response(res); }).catch(function (err) { response(err); }) } export default { get: function (url, params, response) { return apiAxios('GET', url, params, response) }, post: function (url, params, response) { return apiAxios('POST', url, params, response) }, put: function (url, params, response) { return apiAxios('PUT', url, params, response) }, delete: function (url, params, response) { return apiAxios('DELETE', url, params, response) } } 

这里的配置了POST、GET、PUT、DELETE方法。并且自动将JSON格式数据转为URL拼接的方式

同时配置了跨域,不需要的话将withCredentials设置为false即可

并且设置了默认头部地址为:http://localhost:8080/,这样调用的时候只需写访问方法即可

3.使用axios

注:PUT请求默认会发送两次请求,第一次预检请求不含参数,所以后端不能对PUT请求地址做参数限制

首先在main.js中引入方法

import Api from './api/index.js'; Vue.prototype.$api = Api; 

然后在需要的地方调用即可

this.$api.post('user/login.do(地址)', { "参数名": "参数值" }, response => { if (response.status >= 200 && response.status < 300) { console.log(response.data);\\请求成功,response为成功信息参数 } else { console.log(response.message);\\请求失败,response为失败信息 } }); 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/227725.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午8:41
下一篇 2026年3月16日 下午8:41


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号