欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Vue3 结合 .NetCore WebApi 前后端分离跨域请求简易实例

Vue3 结合 .NetCore WebApi 前后端分离跨域请求简易实例

2025/2/1 10:28:54 来源:https://blog.csdn.net/waynesxia/article/details/145395148  浏览:    关键词:Vue3 结合 .NetCore WebApi 前后端分离跨域请求简易实例

1、本地安装Vue3环境

参考:VUE3中文文档-快速上手

注意:初始安装vue时,需要安装router,否则后续也要安装

2、安装axios组件

比如:npm install axios@latest pnpm install axios@latest

3、设置跨域请求代理

打开vue3项目根目录的 vite.config.js文件,插入跨域请求设置

这样实现的效果,假设你的前端域名是 http://localhost:8088

那么你访问 http://localhost:8088/api/hello 等于访问 http://localhost:5153/api/hello

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'export default defineConfig({plugins: [vue(),vueDevTools(),],//跨越请求代理设置server:{proxy: {'/api': {target: 'http://localhost:5153',changeOrigin: true,}
},},resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))},},
})

4、后端.Net Core Webapi 接口返回JSON

using Microsoft.AspNetCore.Mvc;
using MyProj.Models;
using System.Text.Json;
namespace MyProj.Controllers
{[Route("api/login")][ApiController]public class LoginController : ControllerBase{[HttpGet]public JsonResult Get(string pms){//自定义Model,含2个属性。先初始化Rmessage r1 = new Rmessage("hello", "no data");//根据接口请求的参数值判断处理if(pms=="001"){r1.message = "right";}else{r1.message = "wrong";}//把最终的Rmessage实例JSON化返回return new JsonResult(r1);}}
}

5、Vue3前端发送请求,接收返回值

import { ref } from 'vue'
import axios from 'axios'let message = ref('please impress the button')//按钮单击函数
function getApiData() {//axios触发GET请求,传递pms参数axios.get('api/login',{params: {pms:'001'}}).then(response => {//因为返回的是JSON,所以可以response.data直接读取message的值message.value = response.data.message}).catch(error => {console.log(error)})
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com