webapi + vue3 + axios使用

一、安装

npm install axios --save
npm install qs --save

 

二、新建文件utils/request.js 和  utils/http.js

request.js

import axios from 'axios'
import {
    ElMessage,
    ElLoading
} from 'element-plus'
 
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 3 * 1000
})
let loadingInstance;
service.interceptors.request.use(config => {
    loadingInstance = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    config.data = JSON.stringify(config.data);
    config.headers = {
        'Content-Type': 'application/json'
    }
    return config
}, error => {
    Promise.reject(error);
})
 
service.interceptors.response.use(response => {
    loadingInstance.close();
    return response
}, error => {
    loadingInstance.close();
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                error.message = '错误请求'
                break;
            case 401:
                error.message = '未授权,请重新登录'
                break;
            case 403:
                error.message = '拒绝访问'
                break;
            case 404:
                error.message = '请求错误,未找到该资源'
                window.location.href = "/NotFound"
                break;
            case 405:
                error.message = '请求方法未允许'
                break;
            case 408:
                error.message = '请求超时'
                break;
            case 500:
                error.message = '服务器端出错'
                break;
            case 501:
                error.message = '网络未实现'
                break;
            case 502:
                error.message = '网络错误'
                break;
            case 503:
                error.message = '服务不可用'
                break;
            case 504:
                error.message = '网络超时'
                break;
            case 505:
                error.message = 'http版本不支持该请求'
                break;
            default:
                error.message = `连接错误${error.response.status}`
        }
        ElMessage.error(error.message)
    } else {
        if (JSON.stringify(error).includes('timeout')) {}
        error.message = '连接服务器失败'
        ElMessage.error(error.message)
    }
    return Promise.resolve(error.response)
})
export default service

 

http.js

import request from './request'
 
const http ={
    get(url,params){
        const config = {
            method: 'get',
            url:url
        }
        if(params) config.params = params
        return request(config)
    },
    post(url,params){
        const config = {
            method: 'post',
            url:url
        }
        if(params) config.data = params
        return request(config)
    },
    put(url,params){
        const config = {
            method: 'put',
            url:url
        }
        if(params) config.params = params
        return request(config)
    },
    delete(url,params){
        const config = {
            method: 'delete',
            url:url
        }
        if(params) config.params = params
        return request(config)
    }
}
export default http

 

 

 

三、使用

products/index.vue

<template>
<h1>产品管理</h1>
<h1>当前环境:{{apiUrl}}</h1>
<el-button v-on:click="increment()" type="primary">点击</el-button>
<label>{{ this.$store.state.count}}</label>
<el-button @click="showCreate = true" type="primary">新建</el-button>

<el-dialog v-model="showCreate" title="Outer Dialog">
<template #default>
<el-form :model="form" label-width="120px">
<el-form-item label="Activity name">
<el-input v-model="form.name" />
</el-form-item>
</el-form>
</template>
<template #footer>
<div class="dialog-footer">
<el-button @click="showCreate = false">Cancel</el-button>
<el-button type="primary" @click="save()">Save</el-button>
</div>
</template>
</el-dialog>

<div style="margin: 60px;">
<el-table :data="tableData" height="250" style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</div>

<div class="box"> SCSS </div>
</template>
<script>
import http from '../utils/http'
export default {
data() {
return {
count: 0,
showCreate: false,
form: {
name: ''
},
tableData: [{
date: '2016-05-03',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
}],
apiUrl: ''
}
},
methods: {
save() {

this.tableData.push({
date: '2016-05-03',
name: this.form.name,
address: 'No. 189, Grove St, Los Angeles',
});

http.post(`/api/Product`, {
name: this.form.name
}).then(res => {
this.showCreate = false;
this.form.name = '';
console.log(res);
});
},
increment() {
console.log(
import.meta.env);
this.$store.commit('increment');
}
},
mounted() {
this.apiUrl =
import.meta.env.VITE_BASE_URL;
}
}
</script>
<style scoped lang="scss">
@import '../scss/product.scss';

.box {
@include border-radius(12px);
/*未传参数,默认值为5px*/
background-color: #ccc;
border: 1px solid;
}
</style>

 

 

四、WebApi的ProductController 控制器

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
 
namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
 
        [HttpPost(Name = "create")]
        public IActionResult Create([FromBody] ProductInfo productInfo)
        {
 
            return Ok(true);
        }
    }
 
    
    public class ProductInfo
    {
        public string Name { get; set; }
    }
}

 


五、运行效果:

 

 

 

 

 

鸣谢:

https://blog.csdn.net/xiaoxionglove/article/details/125460272

posted @ 2022-07-17 12:11  春光牛牛  阅读(427)  评论(0编辑  收藏  举报