![](/img/trans.png)
[英]Nestjs apply function to each controller function/routes after validation has done
[英]Differentiate 2 routes of a controller (NestJS)
編輯:當我將 @Get('/random') 移動到其他 2 條路線上方時,它正在工作......很奇怪
我正在做一個 NestJS 服務器,它只獲取 Breaking Bad API 的一些路由並在服務器的路由中顯示 JSON,
我想創建 3 條路線:
2 個第一條路線正在工作,但我無法獲得最后一個路線,我收到錯誤 500,顯示錯誤:請求失敗,狀態代碼為 500,目標 url 為“https://www.breakbadapi.com/api/”字符/隨機”,我不知道為什么是“字符”而不是“字符”
這是我的代碼:
characters.controller.ts
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { CharactersService } from './characters.service';
@Controller('characters')
export class CharactersController {
constructor(private readonly charactersService: CharactersService) {}
@Get('/all')
getAll() {
return this.charactersService.getAll();
}
@Get(':id')
getOne(@Param('id') id: string) {
return this.charactersService.getOne(id);
}
@Get('/random')
getRandom() {
return this.charactersService.getRandom();
}
}
characters.service.ts
import axios from "axios";
import { Injectable } from '@nestjs/common';
@Injectable()
export class CharactersService {
getAll() {
return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters`, {
params: {
limit: null,
offset: null,
name: ""
}
}).then(function (response) {
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
getOne(id: string) {
return axios.get(`${process.env.ENDPOINT_BASE_URL}/characters/${id}`).then(function (response) {
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
getRandom() {
return axios.get(`${process.env.ENDPOINT_BASE_URL}/character/random`).then(function (response) {
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
.env
ENDPOINT_BASE_URL=https://www.breakingbadapi.com/api
在 Nest 服務器中,定義的路由順序非常重要。 通過具有@Get(':id')
之前@Get('/random')
你切斷接入/random
因為底層的HTTP引擎將考慮用字符串"random"
為id
為':id'
。
我不知道為什么是“人物”而不是“人物”
如上所述, random
被拉入一個id
而不是路由本身。 將@Get('/random')
路由和處理程序移動到@Get(':id')
應該會為您解決這個問題。
如果您想訪問/character/random
您需要創建另一個提供character
路由的控制器。 例子
@Controller('characters')
export class CharactersController {
constructor(private readonly charactersService: CharactersService) {}
@Get('/all')
getAll() {
return this.charactersService.getAll();
}
@Get(':id')
getOne(@Param('id') id: string) {
return this.charactersService.getOne(id);
}
}
@Controller('character')
export class CharacterController {
constructor(private readonly charactersService: CharactersService) {}
@Get('/random')
getRandom() {
return this.charactersService.getRandom();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.