I want to integrate DHL API into my react js website using node js with express. I have written the backend code and the front end code that would allow me to do this, but when I try to check the rates for a shipment, it gives me this error "Error: Request failed with status code 500"
I don’t know what I am doing wrong when trying to get the DHL API to work.
here is my code:
CheckRates.js:
const [fromCountires,setFromCountries] = useState("");
const [fromCountriesCode,setFromCountriesCode] = useState("");
const [fromCountriesCapital,setFromCountriesCapital] = useState("");
const [toCountries,setToCountries] = useState("");
const [toCountriesCode,setToCountriesCode] = useState("");
const [toCountriesCapital,setToCountriesCapital] = useState("");
const [weight,setWeight] = useState("");
const getRateEstimate = () => {
const options = {
method: 'GET',
url: "http://localhost:3001/api/dhl",
params: {
accountNumber: 'myaccountnumber',
originCountryCode: fromCountriesCode,
originCityName: fromCountriesCapital,
destinationCountryCode: toCountriesCode,
destinationCityName: toCountriesCapital,
weight: weight,
length: '5',
width: '5',
height: '5',
plannedShippingDate: date,
isCustomsDeclarable: 'false',
unitOfMeasurement: 'metric',
},
headers: {
Authorization: 'Basic myauth',
}
};
axios.request(options).then((response) => {
console.log(response.data);
setData(response.data);
}).catch((error) => {
console.error(error);
});
}
nodejs server, index.js:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const multer = require('multer');
const path = require('path');
const request = require('request');
const port = 3001
const app = express();
//Middleware
app.use(cors({
origin: '*',
credentials: true,
methods: ['GET', 'PUT', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",(req,res) => {
res.send("Root App");
})
app.get('/api/dhl', (req, res) => {
request(
{url: 'https://express.api.dhl.com/mydhlapi/test'},
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', });
}
res.json(JSON.parse(body));
}
)
});