axios的封装及跨域代理

一、axios的封装

1.在src中创建utils文件,其下在创建request文件,其中的内容为

(设置跨域后,直接在baseUrl写入写好的路径名)

目录

一、axios的封装

1.在src中创建utils文件,其下在创建request文件,其中的内容为

2.再创建一个HTTP文件,内容为

3.再创建一个api文件,内容为

4.然后直接在页面中写上

二、跨域代理


2.再创建一个HTTP文件,内容为

import http from "./request"

export default function request({ url, method = 'get', data: {}, params: {} }) {
    return http({
        url,
        method,
        data,
        params
    })
}

3.再创建一个api文件,内容为

import request from '../utils/request'

export const addHome = () => request({ url: 'home/shejishi' })

4.然后直接在页面中写上

import { addHome } from "./api.js" 
export default {
    data() {
        return {};
    },
    created() {
        addHome().then(res=>{
            console.log(res);
        })
    },
    methods: {},
    components:{}
};

二、跨域代理

1.原理:协议,端口,域名 有一项不同就会产生跨域

在根目录下创建一个vue.config.js文件,内容为

//修改默认配置,配置跨域
module.exports = {
    devServer: { //开发环境的服务器配置
        proxy: { //代理转发
            "/api": {
                // http://www.sirfang.com/build/ajax_get_list这是完整路径,将com/后的路径重写路径为api
                // 1 目标路径 这里相当于公共的地址
                target: "http://m.sirfang.com/api",
                port: 9090, // 1.1端口号 默认的可以不配
                open: true, // 1.2运行项目自启
                //2 允许跨域
                changOrigin: true,
                //3 重写路径
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}

上一篇:Vue中使用Mock模拟数据测试 (元旦快乐~哈!)


下一篇:Vue安装与简易测试