Search code examples
javascriptnode.jsreactjsserveraxios

Not able to get params from Node.js Server Request by Axios


I am trying to make a simple application which tries to send an SMS. I am using Axios to send a request to the server to send the SMS, and I am using Node.js for the server.

Below given is a snippet of the code of App.js sending the request to server, with parameter NUM which contains the number that twilio (SMS Service) has to send an SMS to

const sendSMSClinic = async () => {
  console.log("CLINIC SMS SENDING FUNCTION ACCESSED");
  try {
    let res = await axios.get("http://localhost:3001/api/mail", {params: {
      NUM: "971561490375"
    }});
  } catch(AxiosError) {
    console.log(AxiosError)
  }
}

Below given is the code of index.js which initiates the node.js server and tries to send an SMS

const express = require('express');
const app = express();
const port = process.env.PORT || 3001;

var cors = require('cors')

app.use(cors())

const accountSid = 'AC8ae163a17e6e3d2ce63e64a98bac68c4'; 
const authToken = '0a13cc33147e4ffb34682097fbf6c49d'; 
const client = require('twilio')(accountSid, authToken); 

app.get('/api/mail/:NUM', async (req, res) => {
    console.log(req.params.NUM);

    client.messages 
        .create({         
            to: '+971561490375',
            from: '+16188160866',
            body: 'REASON FOR CALL: CLINIC EMERGENCY'
        }) 
        .then(message => console.log(message.sid)) 
        .done();
})

app.get("/",(req,res)=>{
    res.status(200).send("successful")
})

app.listen(port, () => {
 console.log('Server is up and running on port ', port);
})

The problem is that I am getting the below errors

GET http://localhost:3001/api/mail?NUM=971561490375 404 (Not Found)

and

AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

Solution

  • You should change your axios request to:

    const num = "971561490375";
    const res = await axios.get(`http://localhost:3001/api/mail/${num}`)
    

    If you want to add multiple path parameters you can edit your end-point declaration to:

    app.get('/api/mail/:NUM/:NUM2', (req, res) => {
        console.log(req.params.NUM, req.params.NUM2);
        ...
    }
    

    And your axios request to:

    const num = "971561490375";
    const num2 = "971561490375";
    const res = await axios.get(`http://localhost:3001/api/mail/${num}/${num2}`);