I am trying to use the value from an object. I don't need to use the 'key' part of the object. Also, I need to remove the curly brackets { } from around the object. How can I do so ?
I'm making a searchbar that sends data into backend, but I only need to use the 'value' part of the object. Perhaps I should use query strings for that ?
const handleClick = (e) => {
e.preventDefault() // stop page from refresh
if (setUserInput !== '') { // is searchbar isnt empty, then run the POST method to send
// data from {userInput} which is the searchbar
const options =
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({userInput}),
};
const response = fetch('http://localhost:3001/search', options);
console.log("search entered");
};
}
in the backend when I console.log the response it gives me
`"{ userInput: 'lollol' }"
and out of all of that I only need the 'lollol' part ( lollol is just an example, but whatever is typed into the searchbar will be shown instead of it ). As such:
const searchResult = req.body /// return lollol ✅
not
const searchResult = req.body /// return `"{ userInput: 'lollol' }" ❌
Should I use query strings to accomplish this, or is there a way to extract data from an object?
CodePudding user response:
You don't need to stringify the object in the body. Replace
body: JSON.stringify({userInput}),
with
body: {userInput:userInput},
And then you can use it like req.body.userInput
.
Hope, it helps!!