Ver*_*ion 2 javascript node.js nestjs
编辑:当我将 @Get('/random') 移动到其他 2 条路线上方时,它正在工作......很奇怪
我正在做一个 NestJS 服务器,它只获取 Breaking Bad API 的一些路由并在服务器的路由中显示 JSON,
我想创建 3 条路线:
两个第一条路线正在运行,但我无法获得最后一条路线, 我收到错误 500,显示错误:请求失败,状态代码为 500,目标网址为“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();
}
}
Run Code Online (Sandbox Code Playgroud)
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
.env
ENDPOINT_BASE_URL=https://www.breakingbadapi.com/api
Run Code Online (Sandbox Code Playgroud)
在 Nest 服务器中,定义的路由顺序非常重要。通过使用@Get(':id')before@Get('/random')来切断对的访问,/random因为底层 HTTP 引擎会将字符串"random"视为idfor ':id'。
我不知道为什么是“人物”而不是“人物”
如上所述,random被拉入的是一条id而不是一条路线本身。将@Get('/random')路由和处理程序移到上面@Get(':id')应该会为您解决这个问题。