0

I'm just starting to learn about HTTP post methods and would like to know if it is possible to get access to variables within the method so that I can export/use it.

Here is my code:

var word = [];
app.post("/search", (req, res) => {;
      console.log(req.body)
      word = req.body["searchedWord"]
    });
console.log(word)

FYI: The req i get looks like { searchedWord: 'soda' }

It currently returns "undefined". If I were to have the console.log(word) within the method, what I want is returned. Any help/tips will be appreciated! Thank you!

  • You are reading the code sequentially and thats why you dont understand whats happening. You need to increase your understanding of how Asynchronous calls work. If there is something that you are trying to achieve please post here or if you generally want to understand whats happening i would suggest you start with https://javascript.info/callbacks – Apoorv Feb 03 '22 at 05:50

1 Answers1

0

it looks like you are getting responses in JSON format so you have to do like this

const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;


instead of it 
 word = req.body["searchedWord"]
Viral Patel
  • 1,104
  • 4
  • 7