helpme
helpme

Reputation: 1

Send params from frontend to be used in a NodeJS Get request

I am trying to pass data to my Node.js backend in order to use it in a get request to an API.

For example:

Server.js

const PORT = 8000
const axios = require('axios').default
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
require('dotenv').config()
app.use(express.json())

app.get('/convertedAmount', (req, res) => {
  const contentBody = req.body

  const options = {
    method: 'GET',
    url: 'https://currency-converter5.p.rapidapi.com/currency/convert',
    params: {format: 'json', from: contentBody.primaryCurrency, to: 
    contentBody.secondaryCurrency, amount: contentBody.primaryCurrencyAmount},
    headers: {
      'x-rapidapi-host': process.env.RAPIDAPI_HOST,
      'x-rapidapi-key': process.env.RAPIDAPI_KEY,
    },
  }

  axios
    .request(options)
    .then((response) => {
      res.json(response.data)
    })
    .catch((error) => {
      console.error(error)
    })
})

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))

The issue is, I don't know how to pass data to the backend from the frontend, without making it a POST request. But that doesn't work if I make a POST request to the rapidAPI url. So the backend needs to stay the same.

My question is, how would I write the frontend part for this?

Using a POST request in the frontend sends the data with the req.body, but I cant get the data to display in my browser on localhost:8000/convertedAmount.

Thank you

My attempt is:

Frontend.js
...

  axios.post('/convertedAmount', {
    primaryCurrency: 'USD',
    secondaryCurrency: 'GBP',
    primaryCurrencyAmount: 1
  })
  .then((response) => {
    console.log(response);
  }, (error) => {
    console.log(error);
  })

...

Upvotes: 0

Views: 3017

Answers (1)

Lee Morgan
Lee Morgan

Reputation: 688

You shouldn't be trying to send data in the body (such as in req.body) through a GET request. That is what a POST request is for.

With a GET request, you should pass data (such as a user id) as a parameter. Basically, in the url string.

FRONTEND

axios.get("/convertedAmount/USD/GBP/1")

BACKEND

app.get("/convertedAmount/:primaryCurrency/:secondaryCurrency/:primaryCurrencyAmount", (req, res)=>{
    console.log(req.params.primaryCurrency);
    console.log(req.params.secondaryCurrency);
    console.log(req.params.primaryCurrencyAmount);
});

Alternatively, you could use query strings, which would look like this:

FRONTEND

axios.get("/convertedAmount?primaryCurrency=USD&secondaryCurrency=GBP&primaryCurrencyAmount=1")

BACKEND

app.get("/convertedAmount*", (req, res)=>{
    console.log(req.query.primaryCurrency);
    console.log(req.query.secondaryCurrency);
    console.log(req.query.primaryCurrencyAmount);
});

Upvotes: 1

Related Questions