简体   繁体   中英

Axios GET route 404-ing, Node.js/Express

I have the following simple GET inside a function.

axios
     .get(`/api/search/q=${this.value}`)
     .then(res => {
            console.log(res.data);
        }); 

The GET 404's if I enter a query (the letter 'a' in this case):

GET http://localhost:7777/api/search/q=a 404 (Not Found)

so, of course I get an Uncaught promise error from the .then:

 Uncaught (in promise) Error: Request failed with status code 404

I figured that it must be a simple routing problem, but my express route is:

router.get('/api/search', someController.someFunction)

The function in the controller works (ie responds with the data) as I have used it elsewhere in the app, so I feel that I have narrowed it down to the axios GET not finding the api. But I can't figure out why, as the path looks OK to me.

You were 404 getting because node is expecting only /api/search but your trying /api/search/:q which is different altogether, try

  axios.get('/api/search/', {
    params: {
      q: value
    }
  })
  .then(function (response) {
      console.log(response);
  })
  .catch(function (error) {
      console.log(error);
  });

since any number of parameters added will not make the URL clumsy, an alternate for

axios.get('/api/search?q=${this.value}'). 

and on the server

router.get('/api/search', someController.someFunction)

and in your controller

if(req.query.hasOwnProperty('q')){
    var q = req.query.q;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM