Search code examples
node-red

How Node-red http response redirect to an URL with msg.payload as a query string


I am new to Node-red and try to use the http response node to redirect a page with query strings.

I read this question and successfully used the header location via change node (I also tried directly set the attribute in http response node) to redirect to an URL. My goal is to redirect to a website with msg.payload as a query string. My msg.payload contains a simply JSON object like

{"id":"1", "condition":2, "nset":3}

I have tried setting the location as http://[redirect_website]/getinfo?{{payload}} but I was redirected to http://[redirect_website]/getinfo?{{payload}} instead of http://[redirect_website]/getinfo?id=1&condition=2&nset=3. Could anyone help me out with this?


Solution

  • You are probably going to have to build the query string yourself.

    So using a function node to set the location header it would be something like:

    msg.statusCode = 303;
    msg.headers = {
        Location: "https://example.com/getinfo?id=" +
        msg.payload.id + "&condition=" +
        msg.payload.condition + "&nset=" +
        msg.payload.nset;
    }
    delete msg.payload;
    return msg;
    

    This code is only safe if all the values are numbers, if some of the values are strings then you need to make sure you URLEncode them before adding them.

    If things get more complicated them you should probably add the querystring module (doc) to the global context (how to add modules to the global context doc) and use this in the function node to generate the query string in one go from the msg.payload object.