0

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?

1 Answer 1

1

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!!

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks a lot. I really liked that idea - however it's throwing a 500 (Internal server error) saying that userInput is not defined on the req.body.userInput server side. That was quite a simple yet thoughtful suggestion. I then removed userInput and now I'm receiving undefined data. Perhaps I need to use some middleware?
Ok, I figiured it out: ``` //To parse URL encoded data app.use(bodyParser.urlencoded({ extended: false })) //To parse json data app.use(bodyParser.json()) ``` The middleware was missing. Thank you !!!
OMG THANKS SO MUCH!!! IT TOOK ME ABOUT A MONTH TO FIGURE THIS OUT - I LOVE YOU, THANK YOU

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.