kube
kube

Reputation: 13954

Azure Functions Redirect Header

I want one of my Azure Functions to do an HTTP Redirection.

This is the current code of the function:

module.exports = context => {
  context.res.status(302)
  context.res.header('Location', 'https://www.stackoverflow.com')
  context.done()
}

But it does not work.

A request sent from Postman shows the response has:

Is this correct code? Or is it simply not allowed by Azure Functions?

Upvotes: 5

Views: 6182

Answers (2)

Mikhail Shilkov
Mikhail Shilkov

Reputation: 35154

The following code works for me:

module.exports = function (context, req) {
    res = {
        status: 302,
        headers: {
            'Location': 'https://www.stackoverflow.com'
        },
        body: 'Redirecting...'
    };
    context.done(null, res);
};

Upvotes: 3

Fabio Cavalcante
Fabio Cavalcante

Reputation: 12538

The code above actually does work, unless you have your binding name set to $return, which is what I assume you have now (you can check in the integrate tab)

Either of the following options will also do what you're looking for

Assuming $return in the binding configuration:

module.exports = function (context, req) {
var res = { status: 302, headers: { "location": "https://www.stackoverflow.com" }, body: null};
context.done(null, res);
};

Or using the "express style" API (not using $return in the binding configuration):

module.exports = function (context, req) {
context.res.status(302)
            .set('location','https://www.stackoverflow.com')
            .send();
};

Upvotes: 12

Related Questions