-1

I have this code:

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));
});

I can't use both res.sendFile and res.send. How can I use both in server.get?

Different approach

If I try something like this it executes only the first code.

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

server.get("/chat", (req, res) => {
    res.sendFile('chat.html', { root: path.join(__dirname, 'public/') });
});

So the result would be getting the rueckgabe but without html page.

123php
  • 307
  • 1
  • 4
  • 17
  • 1
    What do you expect the result of sending a file *and* JSON data to be? An HTTP response can only contain one thing at a time. – deceze Dec 13 '18 at 08:18
  • I want to use `rueckgabe` on my `chat.html` page. If I go to the page `http://localhost/chat?channel=talk` I want to get the page and I want to use the string `rueckgabe` in my `JavaScript` code on client-side. – 123php Dec 13 '18 at 08:20
  • It doesn't really work like that. You probably want to use a templating system to create an HTML file server side and bake the `rueckgabe` data into it, and then just send that one HTML response. – deceze Dec 13 '18 at 08:22
  • That would mean that my `html` code contains `rueckgabe`. This is not what I want. :/ – 123php Dec 13 '18 at 08:27
  • ‍♂️ Sorry, you can't have your cake and eat it too. Either you bake your JSON into the HTML, or you need to serve your JSON in a separate request. Very related: https://stackoverflow.com/a/23740549/476 – deceze Dec 13 '18 at 08:28
  • "or you need to serve your JSON in a separate request" How can I do that? – 123php Dec 13 '18 at 08:36
  • Have separate `server.get` URLs, one which serves the HTML and one which serves the JSON. – deceze Dec 13 '18 at 08:39
  • See my start post, I edited it – 123php Dec 13 '18 at 08:39
  • Well, they need to have *different URLs*. If they're both `/chat`, you can distinguish between them. – deceze Dec 13 '18 at 08:40
  • What is your purpose? What is it which you want? People can't help without recognize your main purpose dude :) – enxtur Dec 13 '18 at 08:47
  • Now I get `{}` as a response from my `ajax` call. I want to call the url `http://localhost/chat?channel=talk` and I want to get `"talk"` the value of my url parameter via `ajax`. And I want the server to serve the `chat.html`. – 123php Dec 13 '18 at 08:47
  • I want to get the `chat.html` page and I want to get the value of the url parameter `channel` which is in this case `talk`. Is this so hard to understand? :D – 123php Dec 13 '18 at 08:51
  • 1
    Hmm, you can get query string from location.search on html page using javascript if got it correct. See this https://www.w3schools.com/jsref/prop_loc_search.asp – enxtur Dec 13 '18 at 08:59
  • Or if you want to do it on server side, you can use template engine. https://expressjs.com/en/guide/using-template-engines.html – enxtur Dec 13 '18 at 09:02
  • I'm thinking about doing it with `location.search`. – 123php Dec 13 '18 at 09:50

2 Answers2

1

You can't use both res.send() and res.sendFile() in the same route and method because every request has only one response and each one is called first, that's your response.

but you can use different method, at first make an ajax post request to 'chat' and get its 'rueckgabe' data in callback then get to your new route like '/chat?data=something'. for example change your code to this: (for more info about params)

server.post("/chat/:channel", (req, res) => {
    let query = req.params;   
    console.log(query.channel);
    let rueckgabe = {
        channel: query.channel
    };
    res.json(JSON.stringify(rueckgabe));
});

server.get("/chat", (req, res) => {
    res.sendFile('chat.html', { root: path.join(__dirname, 'public/') });
});

also you can use in this way but it's strang approach because now you miss your rueckgabe data:

res.send(JSON.stringify(rueckgabe));
// "Warning:" use redirect after send is not routine and usual
res.redirect('/chat');  // redirect to chat with GET method

so it's normal to handle it in client side and make a new request in your response callback.

eerFun
  • 145
  • 8
  • This is my code on client-side on my `chat.html` page: `$.ajax({ type: 'POST', url: '/chat', dataType: "html", success: function (data) { console.log(data); } }); ` Now I get `undefined` in the console on my server and I get `{}` on client-side. – 123php Dec 13 '18 at 09:22
  • use `res.json(JSON.stringify(rueckgabe));` in server side and change your `dataType:'json'` in client. – eerFun Dec 13 '18 at 09:28
  • Still `{}`, which means it works. I get the json data from server-side but it's empty. – 123php Dec 13 '18 at 09:31
  • do you send your 'channel' in your post URL as a query? you can send your data in `body` else and use `body-parser` in server side to parse it. also you should set `contentType: "application/json"` to send json in body from client if you want. – eerFun Dec 13 '18 at 09:35
  • What exactly do you mean by "do you send your rueckgabe in your query"? – 123php Dec 13 '18 at 09:41
  • in your code that i've changed it from GET method to POST, you send data from cilent to server with URL params, so do you send it in URL? if yes, so run `console.log(query)` for debugging – eerFun Dec 13 '18 at 09:45
  • Yes I did already. I use console.log on server-side and this is the result I get `{}` when I call `http://localhost/chat?channel=talk`. – 123php Dec 13 '18 at 09:49
  • may be your url parser not works well, change your code as i update it and get a log from `req.params` may be you found your sent data. – eerFun Dec 13 '18 at 09:56
  • Tried it, doesn't work with `req.params` but this seems to be the solution: https://stackoverflow.com/a/53759247/8582176 – 123php Dec 13 '18 at 10:04
  • ok, glad to help. you can see this for more info about `req.params` and `req.query` https://stackoverflow.com/questions/14417592/node-js-difference-between-req-query-and-req-params – eerFun Dec 13 '18 at 10:11
  • Thank you, I appreciate it. – 123php Dec 13 '18 at 10:12
0

Solution

To get the parameters on client side, you need to use this function:

function searchToObject() {
  var pairs = window.location.search.substring(1).split("&"),
    obj = {},
    pair,
    i;

  for ( i in pairs ) {
    if ( pairs[i] === "" ) continue;

    pair = pairs[i].split("=");
    obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
  }

  return obj;
}

var urlParameters = searchToObject();

If you don't need the url parameters from the server, you can do it this way. urlParameters contains json object with url parameters.

123php
  • 307
  • 1
  • 4
  • 17