I'm fairly new to typescript and trying to make an Express-server run with it. So I'm basically trying to make the following code run after fetching data with axios:
import express, { Response, Request } from 'express'
(...)
app.get('/api/mk', async (req: express.Request, res: express.Response) => {
await axios
.get('http://localhost:8080/rest/kuk/v1/ownerMKKOL/getALL')
.then((axiosResponse) => {
const { data } = axiosResponse
return res.status(200).send(data)
})
.catch((err) => err)
})
I'm however getting the following error message and cannot make much sense out of it:
This expression is not callable. Type 'Number' has no call signatures. TS2349
Do I have to extend the Response-interface? If so, what would a possible solution look like?
Any help is much appreciated!
Solution:
I finally found the solution which basically boiled down to a problem with the structure of my project:
Root
|-- React App
|-- Server
| |-- package.json
| `-- ...
`-- package.json
`-- ...
Somehow when running the build-command from my React App package this problem would appear. I did restructure my project in the following way and the issue did disappear:
Root
|-- Server
| |-- package.json
| |-- express.ts
| `-- ...
`-- Client
|-- package.json
`-- ...
In your code, you are awaiting for a promise result, but you're also registering a callback function for a result and a callback for a failure. This will also return a promise, so the code is correct, but you're not returning the value of it and this is leading to the error.
Also, mixing the .then().catch() way with the await syntax is not easy to read. I would change the code this way:
app.get('/api/mk', async (req: express.Request, res: express.Response) => {
const axiosResponse = await axios
.get('http://localhost:8080/rest/kuk/v1/ownerMKKOL/getALL');
const { data } = axiosResponse;
return res.status(200).send(data);
})
If an exception is thrown, it will be automatically fired and passed to express: it is not strictly necessary to process it, since in your starting code you're not doing anything but throwing it again.