1

For example I have this URL: http://localhost/chat.html?channel=talk How can I get the value of parameter channel in Node.js? I want to store the value of channel in a variable.

I changed server.get to this:

server.get("/channel", (req, res) => {
    let query = url.parse(req.url, true).query;
    console.log(req.query.channel);
    let rueckgabe = {
        channel: req.query.channel
    };
    res.send(JSON.stringify(rueckgabe));
});

Now I'm expecting an output of the value of channel on my console but nothing appears.

This is the full code of index.js:

//Server erstellen
const express = require("express");
let server = express();
server.use(express.static("public"));

//Socket.io
const http = require("http");
let httpServer = http.Server(server);
const socketIo = require("socket.io");
let io = socketIo(httpServer);

//Eventlistener bei Verbindungsaufbau
io.on("connection", (socket) => {
    console.log(socket.id);

    socket.on("chatnachricht", eingabe => {
        io.emit("nachricht", eingabe);
    });
});

let stdIn = process.openStdin();
stdIn.addListener("data", (eingabe) => {
    io.emit("nachricht", eingabe.toString());
});

server.get("/channel", (req, res) => {
    let query = url.parse(req.url, true).query;
    console.log(query);
    let rueckgabe = {
        channel: query.channel
    };
    //res.send(JSON.stringify(rueckgabe));
    res.send(JSON.stringify(rueckgabe));
});

httpServer.listen(80, () => {
    console.log("Server läuft");
});

SOLUTION

This code works so far but with limitations:

//Server erstellen
const express = require("express");
let server = express();
server.use(express.static("public"));

const http = require("http");
let httpServer = http.Server(server);
const socketIo = require("socket.io");
let io = socketIo(httpServer);
var router = express.Router();
const url = require("url");
var path = require('path');


//Eventlistener bei Verbindungsaufbau
io.on("connection", (socket) => {
    console.log(socket.id);

    socket.on("chatnachricht", eingabe => {
        io.emit("nachricht", eingabe);
    });
});

/*
let stdIn = process.openStdin();
stdIn.addListener("data", (eingabe) => {
    io.emit("nachricht", eingabe.toString());
});
*/

server.get("/chat", (req, res) => {
    let query = url.parse(req.url, true).query;
    console.log(query.channel);
    let rueckgabe = {
        channel: query.channel
    };
    res.sendFile('chat.html', { root: path.join(__dirname, 'public/') });
    //res.send(JSON.stringify(rueckgabe));
});

httpServer.listen(80, () => {
    console.log("Server läuft");
});

Now it works with server.get() but I can't use both res.sendFile('chat.html', { root: path.join(__dirname, 'public/') }); and res.send(JSON.stringify(rueckgabe));. How can I use both?

4
  • It's not clear what server is. Are you using express or is this something else? Commented Dec 12, 2018 at 18:32
  • are you using expressjs or native http module of nodejs? Commented Dec 12, 2018 at 18:32
  • Yes I'm using express Commented Dec 12, 2018 at 18:34
  • 2
    Possible duplicate of How to get GET (query string) variables in Express.js on Node.js? Commented Dec 12, 2018 at 18:34

2 Answers 2

1

It looks like you're using the Express framework for Node.

From the docs, query string params may be accessed via req.query:

server.get("/channel", (req, res) => {
    let id = req.query.id; // where "id" is a paramter on the query string
}

And if you need the full URL of the request:

server.get("/channel", (req, res) => {
    let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
}
Sign up to request clarification or add additional context in comments.

6 Comments

server.get("/channel", (req, res) => { let id = req.query.id; // $_GET["id"] } This is not working for me.
@123php Sounds like your query string parameters may be malformed or missing. Also, you do have change id to match the actual parameters used in your query string -- id is just an example.
See my start post
Sorry but console.log(req.query.channel); doesn't appear in my console. I have edited my start post, look at it again.
@123php Yes, you need to replace id with the actual query string parameter in your requests. Try using req.query.channel.
|
0

Well you mentioned for this url http://localhost/chat.html?channel=talk you're not seeing the channel parameter in the server. That's because you aren't hitting the endpoint that you've defined.

Copy of your code from above

server.get("/channel", (req, res) => {
    let query = url.parse(req.url, true).query;
    console.log(req.query.channel);
    let rueckgabe = {
        channel: req.query.channel
    };
    res.send(JSON.stringify(rueckgabe));
});

You're setting the /channel url here. With this configuration if you want to get the query parameter you need to call http://localhost:{portnumber}/channel?channel=somerandomvalue

If you want to have the /chat url change your configuration like this:

server.get("/chat", (req, res) => {
    let query = url.parse(req.url, true).query;
    console.log(req.query.channel);
    let rueckgabe = {
        channel: req.query.channel
    };
    res.send(JSON.stringify(rueckgabe));
});

and call into http://localhost:{portnumber}/chat?channel=somerandomvalue

If you want to serve a static html while using the url name as the same file name you can do something like this:

var router = express.Router();
var path = require('path');

router.get('/chat', function(req, res) {
    // where chat.html is in the public directory
    console.log(req.query.channel);
    res.sendFile('chat.html', { root: path.join(__dirname, '../public/') });
});

20 Comments

Yes I understand. I have chat.html, you didn't mention chat.html in your URLs. If I call this URL http://localhost:{portnumber}/chat?channel=somerandomvalue I'll get an error because chat.html is missing.
You might need to update the /chat with /chat.html then - are you trying to serve a static html page?
I‘m serving a static html page with JavaScript code
If you want to have a back-end code, serving static html is probably not a very good idea. Still - if you want to send a regular html (for now) you can use res.sendFile() - Example here: scotch.io/tutorials/use-expressjs-to-deliver-html-files
To explain this a bit more - the expectation would be to have the url like /chat - but when the user hits /chat url your server would send the static HTML file. All the other stuff (parameters etc...) would be handled in the server side.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.