0

I'm trying to get the value of the query string term=+ e.target.value in the server but it's not showing up. Tried to write the route as '/doSomeSearch?term' and still no req.query.term doesn't show any value in the server. I changed the header from json to 'Content-Type': 'application/x-www-form-urlencoded' but only get 404 error back. Is the route not correct?

Input.js

handleInputBox (e) {
    if(event.keyCode == 13){
        event.preventDefault(); 
        fetch('http://localhost:3000/searchItems?term='+ e.target.value, {
          method: 'POST',
          headers:{
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      },
        ).then(response => {
            if (response.ok) {
             response.json().then(json => {
               console.log("yes")
             });
            }else{
              console.log("no")
            }
          }
      ); 
   }
};

Server.js(Express)

app.get('/doSomeSearch?', function (req, res) {
   console.log(req.query)
})
5
  • Why do you put the question mark in the path? It's a delimiter. But in some/path?term the query parameter doesn't actually have a value. Commented Aug 10, 2019 at 20:24
  • when we are querying, should we not use ? Commented Aug 10, 2019 at 20:25
  • I thought i was sending the value using 'localhost:3000/searchItems?term='+ e.target.value` through e.target.value. then what is the right way of doing it? Commented Aug 10, 2019 at 20:29
  • "searchItems" !== "doSomeSearch" and ? isn't actually part of the route. Give a minimal reproducible example. What's the actual URL you're hitting; is the problem that your frontend is generating the wrong URL (in which case the Express code is irrelevant) or your server has the wrong behaviour for the right URL (in which case the fetch is)? Commented Aug 10, 2019 at 20:33
  • should it not be app.post or the method in fetch should be get? Commented Aug 10, 2019 at 20:35

1 Answer 1

2

the routes should be POST method. As your are hitting a POST method type api and you have GET method configured, express cannot find the signature and return 404.

app.post('/doSomeSearch?', function (req, res) {
   console.log(req.query)
})

This should fix the issue. Hope it helps :)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.