How do I specify a specific get method using axios?
I am currently working with a yarn React application, and one of my front-end components has a form that sends a get request to the backend.
import { useState } from "react";
import axios from "axios";
export default function fld(props){
//set the inital state of the name as null
const [songName, setSongName] = useState(null);
//this function is linked to the GET request,
const handleRetrieve = async (event) =>{
//prevent the page from reloading
event.preventDefault();
//set the formData
const formData = new FormData();
formData.append("songName", songName)
try{
const response = await axios({
method: "get",
url: "http://localhost:8080/",
data: formData
});
console.log(response)
}catch(error){
console.log(error)
}
};
const handleNameSelect = (event ) =>{
setSongName(event.target.name[0]);
};
return(
<form onSubmit={handleRetrieve}>
<label>List out the songs</label>
<input type="text" onChange={handleNameSelect}/>
<input type="submit"/>
</form>
)
}
The thing is, I have multiple get requests in the backend, but only want to fire off the second one. FIRST GET REQUEST:
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
SECOND GET REQUEST (the one I want to fire)
app.get("/Uploadedfiles/:name", (req, res) => {
console.log("GET method: Uploadedfiles/:name")
const params = req.params.name;
let red = read(params);
console.log("reading from folder");
res.send(red);
});
help pls :(
Solution 1:
The only thing you need is to add the endpoint path to the config object in axios like this:
const response = await axios({
method: "get",
url: `http://localhost:8080/Uploadedfiles/${songName}`,
});
Another way to use axios is to use the implicit methods like this:
const response = await axios.get(`http://localhost:8080/Uploadedfiles/${songName}`);
For a complete list of examples on different ways to use axios here is their official docs axios