I'm trying to query an external API with a TS/Express server. Ideally the user will select a product. This will trigger a GET request to the server, which will then submit the query to the external API for price information.
This project is just for fun, and for learning, so please excuse my non-class based approach. It will get refactored into classes, I'm just trying to get this to work for the time being.
// product.route.ts
import { Express } from "express"
import { getProductData } from "../controllers/product.controller"
// We don't need to write products into a DB if we can retrieve pricing via API
// We are not processing payments
// K.I.S.S.
const productRoute = (app: Express) => {
app.get("/api/v1/product", getProductData)
}
export { productRoute }
// product.controller.ts
const getProductData = async (req: Request, res: Response) => {
try {
const query: string = nike
// const { query } = req.body
const api: string = `https://api.exchange.shoes.com/products/${query}/stats`
const response: AxiosResponse = await axios.get(api)
let queryObj = await res.json(response.data)
return queryObj
} catch (error) {
res.json({ error })
}
}
export { getProductData }
When I do the above, it will work. If, I however wanted to make it dynamic and have a form on the front end where a user could enter "adidas," how would I pass that into the api url? I thought I could destructure req.body, and have the front end send { "product": "nike" }, but when I try that I receive a 404.
Any clues or ideas? I'd almost think my route should be a post rather than a get, but you're only supposed to return a 200 w/ a POST. Conversely, you're not really supposed to send a req.body to a GET (you can it's just not that useful).
Small edit: Or, since I do not need to pass credentials to this API endpoint, should I just leave this to the front end and forget about it on the backend.
CodePudding user response:
// product.controller.ts
const getProductData = async (req: Request, res: Response) => {
try {
const { product } = req.body
const api: string = `https://api.exchange.shoes.com/products/${product}/stats`
const response: AxiosResponse = await axios.get(api)
let queryObj = await res.json(response.data)
return queryObj
} catch (error) {
res.json({ error })
}
}
export { getProductData }
Since you decide to send req.body with key name is product
from your front-end
You should change
const {query} = req.body
into
const {product} = req.body
That's mean you must change dynamic variable on your url into product
instead of query