Axios配置跨域、封装get/post请求方法

技术简介

  • Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

安装Axios

 npm install axios

Vue引入Axios配置与请求方法封装

import axios from "axios";
// 超时时间是5秒
axios.defaults.timeout = 5000;
// 允许跨域
axios.defaults.withCredentials = true;
// Content-Type 响应头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
// 基础url
// axios.defaults.baseURL = 后台接口地址;
axios.defaults.baseURL = 线上生产环境地址;

/**
 * 封装get方法
 */
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params: params })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * 封装post方法
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data)
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}

请求后台接口写法

import { get, post } from "./http";
//带参
export const 自定义接口名 = params => get(`后台接口名`, params);
export const 自定义接口名= id => get(`后台接口名?id=${id}`);
// encodeURIComponent可把字符串作为 URI 组件进行Base64编码,使中文在url传输成功
export const 自定义接口名 = 字符串变量名 => get(`后台接口名/` + encodeURIComponent(字符串变量名));
//无参数写法
export const 自定义接口名 = () => get(`后台接口名`);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是封装get和post请求设置cookie,以及在前端 JS 中调用的示例代码: 在后端 Node.js 中,我们可以按照之前的方式封装 get 和 post 请求,并且在实例中设置要发送的 cookie。这里提供一个封装后端 API 的示例代码: ```javascript const axios = require('axios'); const instance = axios.create({ baseURL: 'https://example.com', timeout: 5000, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); instance.defaults.headers.common['Cookie'] = `cookieName=cookieValue`; // 封装 GET 请求 function get(url, params) { return instance.get(url, { params }); } // 封装 POST 请求 function post(url, data) { return instance.post(url, data); } module.exports = { get, post }; ``` 在前端 JS 中,我们可以使用 Ajax 或 fetch 等方式调用后端 Node.js API,获取数据或提交数据。这里提供一个使用 jQuery Ajax 调用后端 API 的示例代码: ```javascript $.ajax({ url: 'https://example.com/api/data', type: 'GET', dataType: 'json', xhrFields: { withCredentials: true }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.error(error); } }); $.ajax({ url: 'https://example.com/api/data', type: 'POST', dataType: 'json', xhrFields: { withCredentials: true }, data: { name: 'John', age: 30 }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.error(error); } }); ``` 在上面的代码中,我们使用了 jQuery 的 `$.ajax()` 方法发送 GET 和 POST 请求,并且设置了 `xhrFields` 选项,让 Ajax 能够携带跨域请求中的 Cookie。在请求成功时,我们通过 `success` 回调函数获取服务器返回的数据,在请求失败时,我们通过 `error` 回调函数获取错误信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【无痕干货营】

如果帮助到您,欢迎打赏一下我

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值