0

I use NextJS and React. My server.js file, looks like this:

const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
  .then(() => {
    const server = express()
    var countrycode = ''

    server.post('/', (req, res) => {
        countrycode = req.body.code
     })

     server.get('/', (req, res) => {
        console.log(res)
        if (countrycode == 'DE') {
            return app.render(req, res, '/de', req.query)
        } else {
            return app.render(req, res, '/', req.query)
        }
      })

    })
  })

i try to save the req.body.code value inside the outside variable var countrycode but it doesn't work. I need to take this step so I can check this value in the server.get function. If the client comes from Germany, the German side should be returned, otherwise the English.

Where is my mistake? What exactly do I need to change? Thanks for your answer

Niklas
  • 1,638
  • 4
  • 19
  • 48
  • Global variables should be defined without `var` in front. – Joost Meijer Oct 01 '18 at 15:05
  • Possible duplicate of [How to access the request body when POSTing using Node.js and Express?](https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express) – Ayush Gupta Oct 01 '18 at 15:06
  • `countrycode` is not used anywhere, just assigned. Perhaps it would be helpful if you try to state what you wish to accomplish with your code. – Jon Koops Oct 01 '18 at 15:11
  • 1
    @JonKoops thanks for your answer, i updated my question. Hope you unterstand me better... – Niklas Oct 01 '18 at 15:20

3 Answers3

1

If you are trying to serve a specific version of your application based on the user's language preference, you can use the Accept-Language header which is sent by the browser. This header contains the preferred languages of the user as configured in the browser. For convenience it I would recommend using some kind of Express middleware like express-request-language.

In your case this could would look something like this:

const express = require('express')
const next = require('next')
const requestLanguage = require('express-request-language')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })

app.prepare()
  .then(() => {
    const server = express()

    server.use(requestLanguage({
      languages: ['en-US', 'de-DE']
    }))

    server.get('/', (req, res) => {
      switch (req.language) {
        case 'de-DE':
          return app.render(req, res, '/de', req.query)
        default:
          return app.render(req, res, '/', req.query)
      }
    })
  })
Jon Koops
  • 8,801
  • 6
  • 29
  • 51
  • thanks for your answer, that could be the solution. Can you tell me this using my `server. js` file, how can I check exactly that? I would be very grateful for that – Niklas Oct 01 '18 at 15:30
  • Yes, I will update the answer shortly with some example code. – Jon Koops Oct 01 '18 at 15:33
  • thank a lot, can you use my example code, so i can use your example directly in my project? I'm just starting to learn node JS that would be really very helpful – Niklas Oct 01 '18 at 15:36
  • Added an example, it is however untested. Let me know if that works for you. – Jon Koops Oct 01 '18 at 15:38
  • thanks a lot for your help, it works now. Do you have an idea how I can set a different page folder for NextJS based on the language? I know that somehow... Otherwise I have the problem and have to check every single page... – Niklas Oct 01 '18 at 15:44
  • You could create a Map that contains which language is associated, or parse the language tag provided by `req.language` (which is a standard BCP47 language tag) and use it's value as the directory name. – Jon Koops Oct 01 '18 at 15:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181091/discussion-between-niklas-and-jon-koops). – Niklas Oct 01 '18 at 16:04
0

It's difficult to be sure without seeing the portion of code where you attempt to use the value stored in countrycode.

My guess is that you're trying to read the value before it is set by the function. For example:

var countrycode;
server.post('/', (req, res) => {
    countrycode = req.body.code
})
console.log(countrycode);

Here, the console output will be undefined, because countrycode will not be set until the POST completes and the function sets its value. To fix this, you should look into using a promise which will only resolve once the value of countrycode has been set.

DukeLion
  • 26
  • 2
0

server.post() is an asynchronous function, which returns immediately and cannot assign values to variables in an outer synchronous code block. Restructure your code to deal with asynchronous behavior:

app.prepare().then(() => {
  const server = express()

  return new Promise((resolve, reject) => {
    server.post('/', (req, res) => {
      resolve(req.body.code);
    })
  });
}).then(countrycode => {
  console.log('server responded with countrycode:', countrycode);
})

Alternatively:

app.prepare()
.then(() => {
  const server = express()

  return new Promise(resolve => {
    server.post('/', (req, res) => {
      resolve(req.body.code);
    })
  })
  .then(countrycode => {
    return new Promise(resolve => {
      server.get('/', (req, res) => {
        console.log(res)
        if (countrycode == 'DE') {
          resolve(app.render(req, res, '/de', req.query))
        } else {
          resolve(app.render(req, res, '/', req.query))
        }
      })
    })
  })
})
Justin
  • 485
  • 5
  • 13
  • thanks a lot for your answer, your Alternatively works, but the `server.get`function doesn't work. I see always the english page, not the german page... do you have an idea for this cause? – Niklas Oct 01 '18 at 15:37