我想使用 axios 和 Nestjs 向外部 api 发出请求。
我使用 axios
接受了 Nestjs 这个答案,而不是在控制器中执行请求,而是创建了一个服务
// controller
import { Controller, Get } from '@nestjs/common';
import { CollectService } from './collect.service';
@Controller('collect')
export class CollectController {
constructor(private collectService: CollectService) {}
@Get()
getResponse(){
this.getResponse();
}
}
// ----------service ------------------------
import { Injectable, HttpService } from '@nestjs/common';
@Injectable()
export class CollectService {
constructor(private httpService: HttpService) {}
async getResponse() {
const response = await this.httpService.get('https://reqres.in/api/users/2').toPromise();
return response.data;
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个 stackoverflow
[Nest] 23928 - 02/28/2021, 12:16:18 PM …Run Code Online (Sandbox Code Playgroud) 根据文档,为了使用 AuthGuard 进行 GraphQL 解析器的身份验证,我们必须重写getRequest如下方法:
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
Run Code Online (Sandbox Code Playgroud)
我的大多数 API 使用 GraphQL,但其他 API 使用 REST 端点来处理文件上传。(我提到了这个)现在,我正在使用两个 AuthGuard。一种是针对 GraphQL,我getRequest像上面一样重写了它。另一种是针对 REST 的,其代码完全相同,除了(这次我没有覆盖它)以及调用后从请求中getRequest提取对象的方式。usercanActivate
图形语言:
// getRequest is overridden
const user: User = this.getRequest(context).user;
Run Code Online (Sandbox Code Playgroud)
休息:
// getRequest is NOT overridden
const { user } = context.switchToHttp().getRequest();
Run Code Online (Sandbox Code Playgroud)
有什么方法可以尝试将这两个 AuthGuard 合二为一吗?
我正在使用 Nest.js,我想导入 auth.parameters.ts 文件中定义的对象。文件定义如下。除非在类中声明以下变量,否则环境变量似乎不可见。
export const obj = {
somevar : process.env.CUSTOM_VAR,
};
Run Code Online (Sandbox Code Playgroud)
在我的其他课程中,我想使用 import {SecurityParameters } from '../auth/auth.parameters' 导入文件
并使用 console.log(SecurityParameters.somevar) 访问该变量。
我可以使用 process.env.CUSTOM_VAR 直接访问变量或
如果我在其他文件中使用 somevar : process.env.CUSTOM_VAR ,我会得到未定义。
我试图在“config.ts”的一个文件中设置所有配置,将其加载到 ConfigService,然后使用配置接口从中获取值。这是我的 config.ts,其中包含 .env 文件中的 ENV 变量和静态变量。
UPD:用这个例子制作了回购协议
import { Config } from './config.interface';
const config: Config = {
typeorm: {
type: 'postgres',
host: process.env.DB_HOST,
port: +process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
synchronize: process.env.NODE_ENV !== 'prod',
logging: true,
entities: [User, RefreshToken],
},
};
export default () => config;
Run Code Online (Sandbox Code Playgroud)
这是我的界面:
export interface Config {
typeorm: TypeOrmConfig;
}
export interface TypeOrmConfig {
type: string;
host: string;
port: number;
username: string;
password: string;
database: string;
synchronize: boolean;
logging: boolean;
entities: any[]; …Run Code Online (Sandbox Code Playgroud) 我创建了一个像这样的守卫
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class CompanyGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = request.headers['token'];
if (token) {
const company = await this.authService.validateToken(token);
return company ? true : false;
} else {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想将 Company 的值保留在请求对象上,以便稍后可以在控制器上使用它。如何在 Nest.js 中做到这一点?我试图在文档中查看它,但我很困惑。我应该使用会话还是有更简单的方法来做到这一点?
我将所有与数据库相关的操作移动到一个独立的模块中:
@Module({
imports: [
TypeOrmModule.forFeature([
PostRepository,
UserRepository,
CommentRepository,
]),
],
exports: [PostRepository, UserRepository, CommentRepository],
providers: [PostsDataInitializer],
})
export class DatabaseModule {}
Run Code Online (Sandbox Code Playgroud)
但是在其他模块中,当我导入DatabaseModule并尝试注入PostRepository服务类时,出现以下错误。
Nest cannot export a provider/module that is not a part of the currently processed module (DatabaseModule).
Please verify whether the exported PostRepository is available in this particular context.
Run Code Online (Sandbox Code Playgroud) 我在express中做了类似的事情来记录mongodb连接事件。
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => console.log('connect to DB successfully :)'));
mongoose.connection.on('error', err => {
console.log('DB connection failed');
});
mongoose.connection.on('disconnected', () => {
console.log('DB disconnected');
});
mongoose.connection.on('reconnected', () => {
console.log('DB reconnected');
});
Run Code Online (Sandbox Code Playgroud)
我想要 Nest js 中有类似的东西,但我做不到。这是我连接到 mongodb 的 Nest js 代码。
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
controllers: …Run Code Online (Sandbox Code Playgroud) 我从nestJS文档(https://docs.nestjs.com/techniques/http-module#http-module)中获取了这个示例,这是我的问题的一个最小示例:
@Injectable()
export class CatsService {
constructor(private httpService: HttpService) {}
findAll(): Observable<AxiosResponse<Cat[]>> {
return this.httpService.get('http://localhost:3000/cats');
}
}
Run Code Online (Sandbox Code Playgroud)
如何从 Observable<AxiosResponse<Cat[]>> 中提取实际的猫数组?我尝试了以下操作,但它给了我一个订阅者对象,我也不知道如何解开该对象以获取实际数据。
const cats = await this.catsService.findAll().subscribe((val) => val);
Run Code Online (Sandbox Code Playgroud) 我一直在阅读和实施很多解决方案,但似乎没有任何效果。
我正在使用 Nestjs ServeStatic 作为他们的官方文档并遵循 StackOverflow 的问题。
但似乎没有任何作用。
到目前为止我的代码
应用程序模块.ts
import { ServeStaticModule } from '@nestjs/serve-static/dist/serve-static.module';
import { join } from 'path';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'public'),
}),
],
controllers: [AppController],
providers: [AppService],
})
Run Code Online (Sandbox Code Playgroud)
我的文件夹结构
/Source
|-public
|--img.jpg
|-src
|--app.module.ts
|--app.controller.ts
|--main.ts
Run Code Online (Sandbox Code Playgroud)
尝试通过访问该文件
http://localhost:3000/public/img.jpg
Run Code Online (Sandbox Code Playgroud)
错误:
[Nest] 3320 - 06/17/2021, 5:24:42 PM [ExceptionsHandler] ENOENT: no such file or directory, stat 'F:\code\dist\public\index.html' +3898ms
Error: ENOENT: no such file or directory, stat 'F:\code\dist\public\index.html'
Run Code Online (Sandbox Code Playgroud)
我一直在关注的问题
我有这个docker-compose.infra.yaml配置:
version: '3.1'
services:
db:
image: postgres
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USERNAME: postgres
networks:
default:
external:
name: learning
Run Code Online (Sandbox Code Playgroud)
连同这个docke-compose.yaml配置:
version: '3.1'
services:
web_app:
container_name: web_app
image: node:14
entrypoint:
["/bin/sh", "-c", "yarn start:dev --preserveWatchOutput"]
working_dir: /app
volumes:
- ./:/app
ports:
- 3001:3000
networks:
default:
external:
name: learning
Run Code Online (Sandbox Code Playgroud)
我将其开始为:
start.infra.sh
#!/bin/bash
docker network create learning
docker-compose -f docker-compose.infra.yaml start
Run Code Online (Sandbox Code Playgroud)
start.sh
#!/bin/bash
docker network create learning
docker-compose up
Run Code Online (Sandbox Code Playgroud)
make start:
.PHONY: start
start:
@./start-infra.sh …Run Code Online (Sandbox Code Playgroud) nestjs ×10
javascript ×4
node.js ×3
typescript ×3
axios ×2
typeorm ×2
auth-guard ×1
docker ×1
express ×1
graphql ×1
mongoose ×1
postgresql ×1
rest ×1