5

【原创】Asp.NET Core Web API与Vue 3.0搭建前后分离项目 - iDream2016

 1 year ago
source link: https://www.cnblogs.com/iDream2018/p/16562523.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【原创】Asp.NET Core Web API与Vue 3.0搭建前后分离项目

特地记录一下,网上的教程写的稀里糊涂的,整得我都心塞塞的,其实实现的过程蛮简单的

问题是这样的:我将Vue构建生成好的文件,放在后端wwwroot文件里面,并开启静态文件访问功能,结果总是无法显示相应的Vue页面,其原因在于路径没有带#,导致路由失败

网上找了很久,很少有这么搭建项目的教程,还是记录一下,算是铺路叭~

后端:Asp.NET Core Web API,版本是 .NET 6

前端:Vue 3 + Vite 

后端WebAPI部分:

1) Program.cs

在app.UseHttpsRedirection();下面添加这两行代码,用来启用静态文件的访问:

app.UseDefaultFiles();
app.UseStaticFiles();

2)控制器代码

在类名的上方添加 [Route("api/[controller]/[action]")]

 [ApiController]
 [Route("api/[controller]/[action]")]
 public class AccountController :  ControllerBase
 {
      //your code
 }    

3) 跨域策略(可有可无)

正常是前端调用后端接口,是不需要配置跨域的,如果有需要,可以在Program.cs添加跨域策略

//添加跨域策略
builder.Services.AddCors(options =>
{
      // 这定义了一个名为 ``default`` 的 CORS 策略
      options.AddPolicy("default", policy =>
       {
             policy.AllowAnyOrigin()
                 .AllowAnyHeader()
                 .AllowAnyMethod();
         });
});

在var app = builder.Build();后面添加使用

 app.UseCors("default");

4)创建一个wwwroot的文件夹,这个文件夹用来放置Vue编译后生成的文件,拷过来放进去就可以

以上就是后端部分要配置的

前端Vue部分

       由于我赶潮流,用上Vue3 + Vite,于是踩上坑了,导致一直访问不到前端的页面,显示404错误。

主要问题在于vue的路由配置方面:vue-router路由版本:4以上,路由代码如下:

import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router';
import home from '../components/home.vue'
const routes = [
 {
    path: '/',
    name: 'Home',
    component:  home
  }
]
 
/**
 * 定义返回模块
 */
const router = createRouter({
  history: createWebHashHistory(), 
  routes
})
 
export default router

注意看上面的history,如果设置为createWebHistory()那么页面的访问路径里面是没有#的,比如 http://baseUrl/Home;

如果设置为createWebHashHistory(),那页面的访问路径就需要带#,比如 http://baseUrl/#/Home

这两者区别非常大!!!

像这种前端是搭配后端WebAPI一起使用的,如果URL没有#这个分隔符,后端服务会将访问的URL路由到相应的控制器上,如果没有对应的控制器,可想而知,它会送你一个404

但是带上#就不一样,URL路由的解析工作是Vue中,由vue-router,这样你配置的路由,才会正确显示对应的页面

这里猜想,不带#的这种形式,应该是为了部署在Nginx、Apache这种服务器使用

最后把Vue项目编译构建后,生成的文件放在后端wwwroot文件夹就好了,它会自动解析的

调用后端API接口时,可以用axios,然后像这样丢过去

import axios from "axios";
function logout() {
    let data={
      Msg:'Hello World'
    }
    axios
    .post("api/Home/Hello",data)
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log("发生异常:" + err);
    });
}

看看 .post("api/Home/Hello",data),Post的地址相当于http://baseurl/api/Home/Hello,也就是说没有出现跨域的情况,前面跨域的配置可有可无

End~

 临时写了demo:https://files.cnblogs.com/files/iDream2018/VueWithWebAPIdemo.rar?t=1659951302

记得用vite创建vue项目 

npm init vite@latest my-vue-app --template vue


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK