receive parameters by url nodejs

1

I would like to be able to receive some parameter by url with nodejs I have tried it this way:

router.get('/events:id', (req,res) => {
var choice = req.params.id;
})

However I get this error:

    
asked by holman sneyder 21.04.2018 в 04:17
source

1 answer

1

In order for you to have the scenario that I propose to you, you must install express with the command npm i -S express and later have a code structure similar to the one I show you

Since you do not specify what technologies you use, I mention the following:

  • Express 4 or higher
  • NodeJS
  • Inside your app.js file write the following:

    const express = require('express')
    
    const app = express()
    
    app.get('/about/:name', (req, res) => {
        res.send('Hello World:' + req.params.name)
    })
    
    app.listen(3000, () => {
        console.log("Running")
    })
    
  • The variable you pass is with the syntax of 2 points and the name of it
  • To invoke and print it is req.params.nombre_variable
  •   

    Remember that so far as I have code it is necessary   Restart the service every time you type something if the changes do not   will be seen with the command node app.js or the name that you have put to your file

    UPDATE

      

    If you want to save the data that arrives in a variable, you just have to do   the next thing is to say your code should look similar to the following

    const express = require('express')
    
    const app = express()
    
    app.get('/about/:name', (req, res) => {
        const name = req.params.name
        res.send('Hello World:' + name)
    })
    
    app.listen(3000, () => {
        console.log("Running")
    })
    
      

    As you can notice in the previous example, I assign the constant name   what is received by req which is the request which in turn reads    params and get the value of the variable that comes by URL called    name

        
    answered by 21.04.2018 / 06:46
    source