Search code examples
node-red

How to make http redirect in node red?


I need to redirect to another url. I am using nodered to request a url, then getting the username and password, checking them in a cloudant database and after veryfing that they are exist, i need to redirect to another /home. Is there a node to redirect?. I tried with http request node, but it just get the response in json or binary not redirecting the url. How to redirect in nodered?


Solution

  • In order to trigger a redirect you need to do two things:

    1. set the status code of the response to the appropriate value
    2. set the location header to the url to redirect to.

    Referring to the help for the HTTP Response node, you can set the status code either directly in the HTTP Response node, or by setting msg.statusCode on the message to pass the node.

    The value you set it to will depend on the type of redirection you want to do - whether its a permanent or temporary redirect.

    For example, a common pattern is to redirect a POST request that creates a resource to a GET request of the new resource. That would be a temporary redirect using 303 as the status code.

    This is a good reference for the different types of redirect code.

    To set the Location header, you can again, either hardcode it in the HTTP Response node, or set it under the msg.headers property.

    For example, a Function node such as the following would do it:

    msg.statusCode = 303;
    msg.headers = {
        Location: "https://google.com"
    }
    delete msg.payload;
    return msg;
    

    You could also use a Change node to do the same:

    enter image description here