'How to get string value from query parameters
I'm trying to get the string value within a class-object variable called question5. I'm trying to access this variable like so in the front-end.
axios.get("http://localhost:3001/users/questionaire/?getquestion5=question5")
.then((res) => console.log(res.data))
Also, this is how it looks inside of the object in the js file.
const [answerslist, setAnswerslist] = useState(
{
question1: "",
question2: "",
question3: "",
question4: "",
question5: "",
question6: "",
question7: "",
question8: ""
}
)
However, when queried and log onto the console from the backend it literally just logs the string 'question5.' In other words, the string is literally just question5 not the text being added to it.
router.route('/questionaire').get((req, res) =>{
console.log(req.query.getquestion5)
User.find({email: req.query.getquestion5}, function (err, docs){
if(docs){
console.log("Email exist")
console.log(`${req.query.getquestion5}`);
console.log(docs)
}
else{
console.log(req.query.getquestion5)
console.log("Email doesnt exist")
}
}).clone().catch(function(err){console.log(err)})
})
Any reason why this might be the case?
Solution 1:[1]
If your intention is to send the answerlist.question5 state value in the query string getquestion5 parameter, try using Axios' params config option
paramsare the URL parameters to be sent with the request
Must be a plain object or a URLSearchParams object
NOTE: params that are null or undefined are not rendered in the URL.
axios.get("http://localhost:3001/users/questionaire", {
params: {
getquestion5: answerslist.question5
}
});
You'd then receive whatever value was in state at the time the request was made into the req.query.getquestion5 property.
Using params is preferable to interpolating strings directly into the URL since it will automatically URL-encode values that otherwise would not be valid. The equivalent safety measure would look like this...
axios.get(
`http://localhost:3001/users/questionaire?getquestion5=${encodeURIComponent(answerslist.question5)}`
);
which gets unmaintainable with more parameters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
