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?

123php
  • 307
  • 1
  • 4
  • 17

2 Answers2

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;
}
Elliot B.
  • 17,060
  • 10
  • 80
  • 101
  • `server.get("/channel", (req, res) => { let id = req.query.id; // $_GET["id"] }` This is not working for me. – 123php Dec 12 '18 at 18:38
  • @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. – Elliot B. Dec 12 '18 at 18:41
  • See my start post – 123php Dec 12 '18 at 18:49
  • Sorry but `console.log(req.query.channel);` doesn't appear in my console. I have edited my start post, look at it again. – 123php Dec 12 '18 at 18:51
  • @123php Yes, you need to replace `id` with the actual query string parameter in your requests. Try using `req.query.channel`. – Elliot B. Dec 12 '18 at 18:53
  • I did and it's not working. :( There is no output on my console. – 123php Dec 12 '18 at 18:54
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/') });
});
Mavi Domates
  • 4,262
  • 2
  • 26
  • 45
  • 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. – 123php Dec 12 '18 at 20:27
  • You might need to update the /chat with /chat.html then - are you trying to serve a static html page? – Mavi Domates Dec 12 '18 at 20:34
  • I‘m serving a static `html` page with `JavaScript` code – 123php Dec 12 '18 at 20:36
  • 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: https://scotch.io/tutorials/use-expressjs-to-deliver-html-files – Mavi Domates Dec 12 '18 at 20:39
  • 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. – Mavi Domates Dec 12 '18 at 20:42
  • I want the URL to be chat.html?channel=talk or /chat?channel=talk and I want to serve chat.html. How can I get this running? – 123php Dec 12 '18 at 20:48
  • In PHP it‘s just so easy. – 123php Dec 12 '18 at 20:49
  • Updated my answer – Mavi Domates Dec 12 '18 at 20:52
  • Is `router` a module? – 123php Dec 12 '18 at 20:56
  • Updated my answer again. This should work with /chat?channel=talk – Mavi Domates Dec 12 '18 at 21:10
  • Changed it to: `router.get("/chat.html", (req, res) => { let query = url.parse(req.url, true).query; console.log(req.query.channel); let rueckgabe = { channel: req.query.channel }; res.sendFile('public/chat.html'); res.send(JSON.stringify(rueckgabe)); });` Doesn't work, still no output on my console. This is the URL: `http://localhost/chat.html?channel=talk` – 123php Dec 12 '18 at 21:13
  • Can you change it to /chat please? - and I've updated the code – Mavi Domates Dec 12 '18 at 21:15
  • I changed it to /chat and now I get an error: `Cannot GET /chat` – 123php Dec 12 '18 at 21:15
  • Yes I did. You mean this: `res.sendFile('chat.html', { root: path.join(__dirname, '../public/') });` – 123php Dec 12 '18 at 21:22
  • yes? Please make sure the about this part: router.get('/chat' – Mavi Domates Dec 12 '18 at 21:24
  • I've added the printing of the parameter as well. This should work - I have it working here. – Mavi Domates Dec 12 '18 at 21:28
  • For me it's not working. This is the code I have so far: `router.get("/chat", (req, res) => { //let query = url.parse(req.url, true).query; console.log(req.query.channel); let rueckgabe = { channel: req.query.channel }; res.sendFile('public/chat.html'); res.send(JSON.stringify(rueckgabe)); });` index.js is in folder websockets and inside of websockets there is a folder public with chat.html inside. – 123php Dec 12 '18 at 21:32
  • I'll ask my teacher tomorrow. :/ But thank you for your help. I appreciate it. :) – 123php Dec 12 '18 at 21:47
  • I got it working but with limitations, see my code in my start post. Maybe you have an idea? – 123php Dec 13 '18 at 08:01
  • You can’t use both. You are sending only one response which is the html, you can’t send both the html and the json as separate responses to the same request – Mavi Domates Dec 13 '18 at 08:57