我想提供/dist位于 Nest 项目外部文件夹中的静态 HTML 文件。index.html已成功加载但无法加载任何 JS 文件(404错误)。
我有一个 Node/Express.js 项目,它使用
app.use('/', express.static('../client/dist'))
Run Code Online (Sandbox Code Playgroud)
它工作得很好。
然而,在 Nest 项目中,
app.setBaseViewsDir(join(__dirname, '../../client/dist'))
Run Code Online (Sandbox Code Playgroud)
不做的伎俩。
在AppController我试过
import { Response } from 'express';
@Get()
get(@Res() res: Response) {
res.sendFile('index.html', {
root: '../client/dist',
});
}
Run Code Online (Sandbox Code Playgroud)
但没有运气。
如前所述,index.html已成功加载。所以问题不是走错路。问题也不是 src-paths 错误,index.html因为在 Express 项目中使用了完全相同的文件。
/dist
|-index.html
|-main.js
|-etc.
Run Code Online (Sandbox Code Playgroud)
在 index.html 中:
<script type="text/javascript" src="main.js"></script>
Run Code Online (Sandbox Code Playgroud)
当我将 dist 文件夹放入 Nest 项目(并调整路径)时,它也不起作用。
我现在使用 express 模块:
import * as express from 'express'; …Run Code Online (Sandbox Code Playgroud) 我的.envNestJs 项目的根目录中有一个文件,其中包含一些 env 变量。
奇怪的是,我能够读取服务文件中的变量,但不能读取模块文件中的变量。
所以在像这样的服务文件中users.service.ts,这有效:
saveAvatar() {
const path = process.env.AVATAR_PATH // returns value from .env
}
Run Code Online (Sandbox Code Playgroud)
但是,当访问模块文件中的路径时,如auth.module.ts,这将返回一个空值:
@Module({
imports: [
JwtModule.register({
secretOrPrivateKey: process.env.SECRET // process.env.SECRET returns an empty string
})
]
})
Run Code Online (Sandbox Code Playgroud)
为什么呢?如何.env在 NestJs 中可靠地访问文件中的环境变量?
NestJS 使用默认记录器实现。它将输出发送到控制台。
我可以知道,如何配置默认记录器以将输出发送到文件、数据库。
此外,
如果我想在 NestJS 中使用 Winston,如何使用/注入/扩展各种传输选项。
它不应该与 NestJS 紧密耦合,并且始终能够替换为其他一些记录器。
我想开始使用 NestJs 创建 REST API,但我不确定如何设置可扩展的层通信对象。
因此,从有关如何开始的文档中,我提出了UsersController处理 HTTP 请求和响应的方法,UsersService处理控制器和数据库访问器之间的逻辑以及UsersRepository负责数据库管理的方法。
我使用NestJs提供的TypeORM 包,所以我的数据库模型是
@Entity('User')
export class UserEntity extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
username: string;
@Column()
passwordHash: string;
@Column()
passwordSalt: string;
}
Run Code Online (Sandbox Code Playgroud)
但是您可能知道,这个模型必须映射到其他模型,反之亦然,因为您不想将密码信息发送回客户端。我将尝试用一个简单的例子来描述我的 API 流程:
控制器
首先,我有一个用于GET /users/:id和的控制器端点POST /users。
@Get(':id')
findById(@Param() findByIdParamsDTO: FindByIdParamsDTO): Promise<UserDTO> {
// find user by id and return it
}
@Post()
create(@Body() createUserBodyDTO: CreateUserBodyDTO): Promise<UserDTO> {
// create a …Run Code Online (Sandbox Code Playgroud) 我需要一些有关迁移的帮助。我正在尝试使用迁移来播种数据库。但我收到错误“QueryFailedError:关系“帐户”不存在”。我认为这只是典型的新手错误。所以请检查我的代码:
帐户.实体.ts
import { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';
import { AbstractEntity } from '../../common/abstract.entity';
import { SourceEntity } from '../source/source.entity';
import { UtilsService } from '../../shared/services/utils.service';
@Entity({ name: 'account' })
export class AccountEntity extends AbstractEntity {
@Column({ unique: true })
username: string;
@Column({ nullable: true })
password: string;
@OneToMany(() => SourceEntity, (source) => source.account, {
cascade: true,
})
sources: SourceEntity[];
@BeforeInsert()
async setPassword() {
this.password = UtilsService.generateHash(this.password);
}
}
Run Code Online (Sandbox Code Playgroud)
种子数据.migration.ts
import { getCustomRepository, MigrationInterface, QueryRunner } from …Run Code Online (Sandbox Code Playgroud) 我目前正在使用 Mongoose 和 NestJs,并且在访问createdAt属性方面遇到了一些困难。
这是我的 user.schema.ts
@Schema({ timestamps: true})
export class User {
@Prop({ required: true })
name!: string;
@Prop({ required: true })
email!: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
Run Code Online (Sandbox Code Playgroud)
在我的 user.service.ts 中
public async getUser(
id: string,
): Promise<User> {
const user = await this.userModel.findOne({ id });
if (!user) {
throw new NotFoundException();
}
console.log(user.createdAt) // Property 'createdAt' does not exist on type 'User' .ts(2339)
}
Run Code Online (Sandbox Code Playgroud)
所以基本上我已经将时间戳设置为 true 但我仍然无法访问createdAt属性。顺便说一句,我还有一个可以正常工作的自定义 id,因此请在我的 service.ts 中忽略它
我已经尝试设置@Prop() createdAt?: Date架构,但仍然不起作用。
我还使用 …
我想像下面这样在nestjs中禁用X-Powered-By,但它不起作用。
主要.ts:
async function bootstrap() {
const logger = new Logger('bootstrap')
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.disable('X-Powered-By') // this line
...
const PORT = process.env.PORT
await app.listen(PORT);
logger.log(`Application is start on port : ${PORT}`)
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
禁用X-Powered-By标头后,在下一个请求中,该X-Powered-By标头仍然存在。
我哪里做错了什么?
我尝试用对象数组映射一个键字符串。
我可以创建一个简单的对象,但我想在这些数组中轻松添加一个对象。地图对象非常适合执行此操作。
问题:我不知道如何为 GraphQL 定义类型映射 :'(
@ObjectType()
export class Inventaire
@Field()
_id: string;
@Field()
stocks: Map<string, Article[]>;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试对使用弹性搜索的服务进行单元测试。我想确保我使用了正确的技术。
我是这个问题许多领域的新用户,所以我的大部分尝试都是通过阅读与此类似的其他问题并尝试在我的用例中有意义的问题。我相信我缺少 createTestingModule 中的一个字段。也有时我看到providers: [Service]和其他人components: [Service]。
const module: TestingModule = await Test.createTestingModule({
providers: [PoolJobService],
}).compile()
Run Code Online (Sandbox Code Playgroud)
这是我当前的错误:
Nest can't resolve dependencies of the PoolJobService (?).
Please make sure that the argument at index [0]
is available in the _RootTestModule context.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
池作业服务
Nest can't resolve dependencies of the PoolJobService (?).
Please make sure that the argument at index [0]
is available in the _RootTestModule context.
Run Code Online (Sandbox Code Playgroud)
PoolJobService.spec.ts
import { Injectable } from '@nestjs/common'
import { ElasticSearchService } from …Run Code Online (Sandbox Code Playgroud) 我有一个使用 typescript 的节点应用程序,我正在尝试按照 TypeORM 的文档创建一个新的迁移。
首先,我安装了CLI,像这样设置我的连接选项,当我尝试运行此命令时:
npm run typeorm migration:create -- -n migrationNameHere
我收到以下错误:
迁移创建过程中出错:类型错误:无法读取对象中未定义的属性“startsWith”。(...\src\commands\MigrationCreateCommand.ts:62:37) 在步骤 (...\node_modules\typeorm\node_modules\tslib\tslib.js:141:27) 在 Object.throw (...\node_modules \typeorm\node_modules\tslib\tslib.js:122:57) 在被拒绝 (...\node_modules\typeorm\node_modules\tslib\tslib.js:113:69) npm ERR!代码 ELIFECYCLE npm ERR!错误号 1 npm 错误号!backend@0.0.1 typeorm: node --require ts-node/register ./node_modules/typeorm/cli.js "migration:create" "-n" "migrationNameHere"` npm ERR!退出状态 1
这些是我在 package.json 中的嵌套依赖项:
我的节点版本是v12.14.1,nestjs 是7.0.0和 nestjs/typeorm 是7.1.3
我的 app.module.ts 是这样的:
TypeOrmModule.forRoot({
type: 'mysql',
host: database().host,
port: parseInt(database().port),
username: database().username,
password: database().password,
database: database().schema,
entities: [Question, QuestionOption],
migrations: ['migration/*.js'],
cli: …Run Code Online (Sandbox Code Playgroud) nestjs ×10
node.js ×6
typescript ×5
javascript ×3
graphql ×2
typeorm ×2
database ×1
dotenv ×1
express ×1
logging ×1
mongodb ×1
mongoose ×1
npm ×1
postgresql ×1
static-files ×1
typegraphql ×1
winston ×1