I need to get a list from this resource http://jsonplaceholder.typicode.com/photos
Controller
@JsonController('/photo')
@Service()
export class PhotoController {
constructor(private photoService: PhotoService) {}
@Get('/load-photos')
loadPhoto() {
return axios
.get('http://jsonplaceholder.typicode.com/photos')
.then(async (response) => console.log(response.data.slice(0, 8)))
.catch((e) => console.log(e));
}
}
Postman rout: http://localhost:5000/photo/load-photos
As soon as I try to just try to make a request through axios for a resource through postman, I call the controller and I get the error that I give below. If I do an action outside the application, then through axios I can easily get data into the console, for example.
Error
Error:
at new HttpError (C:\pet-project\express\node_modules\src\http-error\HttpError.ts:16:18)
at new NotFoundError (C:\pet-project\express\node_modules\src\http-error\NotFoundError.ts:10:5)
at ExpressDriver.handleSuccess (C:\pet-project\express\node_modules\src\driver\express\ExpressDriver.ts:324:15)
at C:\pet-project\express\node_modules\src\RoutingControllers.ts:164:35
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Application class:
export class App {
public app: express.Application;
constructor() {
this.app = express();
}
public async createExpressServer(port: number) {
useContainer(Container);
useExpressServer(this.app, {
controllers: [AuthController, PhotoController],
middlewares: [],
authorizationChecker: async (action: Action, roles?: string[]): Promise<boolean> => {
return false;
}
});
this.app.listen(port, () => console.log(`Running on port ${port}`));
}
}
call app:
const app = new App();
const port: any = process.env.APP_PORT;
app.createExpressServer(5000);
What do I use in the application: Express and routing-controllers libs
Question: Why am I getting this error when trying to get data from a resource from a controller? Thanks in advance for your reply!
CodePudding user response:
You didn't return a proper non-empty result or a Promise with such result that's why you got a 404 error as the official documentation says.
Try to get a result with await
and return it explicitly:
@JsonController('/photo')
@Service()
export class PhotoController {
constructor(private photoService: PhotoService) {}
@Get('/load-photos')
async loadPhoto() {
try {
const { data } = await axios
.get('http://jsonplaceholder.typicode.com/photos');
return data.slice(0, 8)
} catch (e: Error) {
console.log(e)
// returns 404 for instance, it's up to you,
// see https://github.com/typestack/routing-controllers#throw-http-errors
throw new NotFoundError(`Photos were not found.`);
}
}
}