user3287470
user3287470

Reputation: 27

NodeJS get params from URL -> httprequest and express both not working

I'm running a NodeJS application and am visiting it at localhost/?product=test. I want to retreive 'test' (or any URL-related information for that matter).

Google shows me 2 options, but I can't get either to work:

  1. Use HttpRequest
    const http = require('http');
    const url = require('url');

    http.createServer(function (req, res) {
      const queryObject = url.parse(req.url,true).query;
      console.log(queryObject);

      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('Feel free to add query parameters to the end of the url');
    }).listen(3000);

I'm trying to use this code, or variations on it, but the issue is that I cannot create a server to listen to because the address is already in use. I'm not too familiar with NodeJS, but what I don't understand is how to use a HttpRequest properly to listen to the running application and get its URL.

  1. Use Express

Using express doesn't give an error, but all code snippets that -should- work return undefined for me when retrieving the URL.

What is a simple way to retrieve the URL the user used to visit my NodeJS app, so I can retrieve the parameters?

Upvotes: 0

Views: 60

Answers (1)

ktad
ktad

Reputation: 301

If you want to access localhost without filling in a port like here localhost/?product=test then you should listen to port 80 and not 3000. Otherwise your request should look like this: localhost:3000/?product=test

You should also create a route method for products. In express it will look like this:

const express = require('express')
const app = express()
const port = 80

app.get('/', (req, res) => res.send('home'))

app.get('/product/:productId', function (req, res) {
  res.send(req.params)
})

app.listen(port, () => console.log(`Listening on port ${port}!`))

If you run this example your request url should be http://localhost/product/test and response will look like

{
  "productId": "test"
}

Upvotes: 1

Related Questions