Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

422
Visualizações
Getting Undefined When Trying to Request Const Data From Reactjs File in my NodeJS Express API

I have a file named check-rates that holds some useStates() that the users will input in order for me to execute and return for them an estimated value for their shipment by using DHL API.

In my nodejs express server, I am trying to access these useStates() with req.body but when I console log the constants I always get them as undefined. I need these values that the user enters so that the API becomes dynamic for each customer/user that uses my website and not fixed values (as I have them now.)

What am I doing wrong?

here is my code:

Check-Rates.js:

const [fromCountires,setFromCountries] = useState("");
const [fromCountriesCode,setFromCountriesCode] = useState("");
const [fromCountriesCapital,setFromCountriesCapital] = useState("");
const [fromPostalCode,setFromPostalCode] = useState("");
const [toCountries,setToCountries] = useState("");
const [toCountriesCode,setToCountriesCode] = useState("");
const [toCountriesCapital,setToCountriesCapital] = useState("");
const [weight,setWeight] = useState("");
const [data,setData] = useState(null);

 const getRateEstimate = () => {
    
        axios.get('http://localhost:3001/api/dhl').then(response => {
            console.log(response)
            setData(response.data);
        }).catch(e => {
            console.log(e)
        });
    }

return (
 //example of how i am setting my needed useStates...
<Form.Group controlId="exampleForm.ControlInput1">
   <Form.Label className={'fw-bold'}>Weight</Form.Label>
   <Form.Control type="text" placeholder="" onChange={(e)=> {
     setWeight(e.target.value)}}/>
 </Form.Group>

  <button className={'btn-orange fw-bold py-2 px-3 px-4 rounded getRateBtn'}
  type={'submit'} onClick={getRateEstimate}> Check
  </button>
)

NodeJS Server

index.js:

app.get('/api/dhl', (req, res) => {

    const accountNum = req.body.accountNum
    const fromCountriesCode = req.body.fromCountriesCode
    const fromCountriesCapital = req.body.fromCountriesCapital
    const toCountriesCode = req.body.toCountriesCode
    const toCountriesCapital = req.body.toCountriesCapital
    const weight = req.body.weight
    const plannedShippingDate = req.body.date
    const len = "5"
    const width = "5"
    const height = "5"
    const isCustomsDeclarable = 'false'
    const unitOfMeasurement = 'metric'

    console.log(weight)//logs undefined
    console.log(fromCountriesCapital)//logs undefined

    var options = { method: 'POST',
    url: 'https://express.api.dhl.com/mydhlapi/test/rates',
    headers: 
     { 'postman-token': '',
       'cache-control': 'no-cache',
       authorization: 'Basic AUTH',
       'content-type': 'application/json' },
    body: 
     { customerDetails: 
        { shipperDetails: 
           { postalCode: '19010',
             cityName: 'Dubai',//need this
             countryCode: 'BH',//need this
             addressLine1: '0' },//end Shipper DETAILS
          receiverDetails: 
           { postalCode: '76321',
             cityName: 'Riyadh',//need this
             addressLine1: '0',
             countryCode: 'SA' }//end Reciever DETAILS
             },
       accounts: [ { typeCode: 'shipper', number: 'myAccountNumbeer' } ],
       plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//need thiss
       unitOfMeasurement: 'metric',
       isCustomsDeclarable: true,
       monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
       requestAllValueAddedServices: false,
       returnStandardProductsOnly: false,
       nextBusinessDay: false,
       packages: [ { weight: 25, dimensions: { length: 5, width: 5, height: 5 } } ] },
    json: true };
  
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    res.send(body)
    console.log(body);
  });
});
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

try {
   const res = await axios.get("/api/dhl", {
       data: {
            product: this.product
       }
   })
} catch (error) {
   console.log(error)
}

More informations

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda