nestjs + vue 开发

232 阅读1分钟

nestjs项目初始化

安装nestjs并初始化项目

$ npm i -g @nestjs/cli
$ nest new project-name

项目创建成功后,主要的文件都在src目录下

image.png

为了配合vue使用,给请求加上api前缀。为了能使用console.log,需要在项目main.ts文件中的bootstrap函数内设置logger。

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: console // 支持使用console.log等函数
  });
  
  app.setGlobalPrefix('api'); // 给所有的请求加上/api前缀
  await app.listen(3000);

  if(module.hot){
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}

初始化vue项目

project-name项目内,安装vue-cli并创建client项目

npm install -g @vue/cli
vue create client

在开发过程中,为了变更后能自动更新,就不使用build好的文件,直接启动vue项目。为了能够访问到nestjs项目提供的api,设置vue.config.js中的proxy

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: 'http://localhost:3000'
  }
})

请求

post请求

在vue中可以直接使用fetch构建post请求

const myHeaders = new Headers();
myHeaders.append('Content-Type', "application/json");
await fetch('/api/user', {
    method: 'POST',
    headers: myHeaders,
    body: JSON.stringify({
      name: 'joy'
    }),
});

在nestjs中的constroller中接收参数并返回

@Post('/user')
create(@Req() req, @Res() res: Response) {
    const { name } = req.body
    res.status(HttpStatus.OK).send(name);
}