Thermetro
Thermetro

Reputation: 51

req.query undefined in Nuxt Express Middleware get request

Not a pro with things like server middleware, but stuck without much clues.

In a vue component I am retrieving data with axios with this:

  axios
    .get('/api/getDailyFeedback', {
      params: {
        start: '2018-05-01'
      }
    })

Which goes to the express (version 4.16.2) server middleware setup in Nuxt. I have gotten normal get and post requests to work fine but the problem is when I want to pass in a parameter into a get request like the below:

router.get('/getDailyFeedback', (req, res) => {
   console.log('Query:', req.query.start);
   //do stuff
});

What little experience I had with Express 4, it took me a little bit of time to realise why parameters passed in the body of a post request were undefined, but it was because I needed to add body-parser.json() to my nuxt config since they removed that from the main express package. Similarly I thought I needed bodyParse.urlencoded but that has not worked. This is the line I added to my nuxt.config:

serverMiddleware: [bodyParser.urlencoded({ extended: false }), bodyParser.json(), '~/api'],

I am unsure if the content type is not set correctly or I am missing something simple here. I know I am able to use various libraries to grab the parameters from the url string which I have access to, as Axios is working as expected and adding my 'params' object onto the end of my get request. But a lot of solutions I have seen to other problems is 'oh its as simple as accessing req.query' Alas Express fails to define a req.query object, or even req.params or req.body.

Hopefully that is enough detail to go on, thanks a lot for reading and any suggestions.

Upvotes: 4

Views: 4708

Answers (4)

heesel
heesel

Reputation: 58

For anyone else in the future

const { Router } = require('express')

Router.get('/orders', async (req, res, next) => {
    const request = req.query.sometext;
    res.json({data: request});
});

module.exports = Router;
<script>
    export default() {
        async mounted() {
            const orders = await axios.get(`/api/orders`, {
                params: {
                    sometext: 'bla bla'
                }
            });
       }
   }
</script>

http://expressjs.com/en/api.html#req

Upvotes: 0

Van Zelleb
Van Zelleb

Reputation: 21

I am using Nuxt 2.15 and I can access the query parameter like this req._parsedOriginalUrl.query

Upvotes: 2

Nolog
Nolog

Reputation: 1

You can access Nuxt get params without additional modules. Just use:

req.request.get()

Upvotes: 0

Hexodus
Hexodus

Reputation: 12927

Well that's an unpleasant surprise to try to use the get request in Nuxt for the first time, isn't it? Nuxt creates a connect instance which leads to some pitfalls. It's req is the Node.js http request object, so it doesn't have the query property and request.body is also being skipped in get requests!

But there is a way for everything. Your code:

  axios.get('/api/getDailyFeedback', {
      params: {
        start: '2018-05-01'
      }
    })

Translates to the following URI call:

/api/getDailyFeedback?start=2018-05-01

So you've got all the params in the URI where you can retrieve them from via url parsing. Module url ships with Node.js by the way.

const url = require("url");

router.get('/getDailyFeedback', (req, res) => {
   let queryData = url.parse(req.url, true).query
   console.log('Query:', queryData.start)
});

I wrote a little helper that extends req with a custom property. Here's the code:

router.use((req, res, next) => {
  var theQuery = url.parse(req.url, true).query
  req.queryData = theQuery 
  next()
})

Then you can use it like this:

router.get('/getDailyFeedback', (req, res) => {
   console.log('Query:', req.queryData.start)
});

Other way to pass params via get is by using optional uri segments:

router.get('/getDailyFeedback/:start?', (req, res) => {
   console.log('Query:', req.params.start)
});

Upvotes: 7

Related Questions