前言
本文是客户端开发的下一节,欢迎掘友和小雨一起敲代码,下面是配置服务端的实战。
2.服务端
安装nest
npm i -g @nestjs/cli
以管理员身份运行powerShell(一定要以管路员身份打开)
set-ExecutionPolicy RemoteSigned
创建nest项目,在node文件夹打开命令行输入下面命令,选择npm
nest new nest-login
修改src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3001);//不要与前端运行端口一致
}
bootstrap();
运行项目
npm run start:dev
建立src/models/result.model.ts,用于统一返回数据
export class ResultModel<T>{
data:T
code:number
msg:string
constructor(code:number,data:T,msg:string){
this.code=code
this.data=data
this.msg=msg
}
}
建立src/controller/user.controller.ts,用于业务处理
import { Controller, Get, Query } from '@nestjs/common'
import { ResultModel } from 'src/models/result.model';
import { UserService } from '../service/user.service'
@Controller('/user')
export class UserController {
constructor(private readonly userService: UserService) { }
@Get("/login")
login(@Query('username') username:string,@Query('password') password:string):ResultModel<object> {
return this.userService.login(username,password);
}
}
建立src/service/user.service.ts,用于处理业务
import {Injectable} from '@nestjs/common'
import { ResultModel } from 'src/models/result.model';
@Injectable()
export class UserService{
login(username:string,password:string):ResultModel<object>{
let obj = {
username:'admin',
password:'123',
name:'admin'
}
if(obj.username == username && obj.password == password){
return new ResultModel(
200,
{userInfo:obj,
token:"abc"
},
'登录成功')
}else{
return new ResultModel(500,null,'账号或密码错误')
}
}
}
建立src/module/user.module.ts,用于处理业务和服务
import { Module } from "@nestjs/common";
import { UserController } from "src/controller/user.controller";
import { UserService } from "src/service/user.service";
@Module({
imports:[],
controllers:[UserController],
providers:[UserService],
})
export class UserModule{}
配置src/app.modul.ts
import { Module } from '@nestjs/common';
import { UserModule } from './moudle/user.module';
@Module({
imports: [UserModule],
})
export class AppModule {}
配置src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('/api');//配置公共访问路径
await app.listen(8080);//与前端listen的端口一致
}
bootstrap();
服务端配置成功,项目结构
3.效果
运行vite-project项目
npm run dev
登录界面,展示登录失败
登录成功界面
总结
前端不再是写写界面那么简单了,前端也可进行全栈开发,前端也可以CRUD,不只有MVVM,也有MVC和ORM。
常用Java开发的小雨发现了新大陆,node.js牛逼~
掘友你学会了吗?
有不懂得?遇到问题?评论区见~