Javascript 如何在 express js 中执行 res.redirect 时传递标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39997413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:08:06  来源:igfitidea点击:

How to pass headers while doing res.redirect in express js

javascriptnode.jsexpress

提问by user3655266

I am working on express js and I need to redirect to a page which needs authentication. This is my code:

我正在处理 express js,我需要重定向到需要身份验证的页面。这是我的代码:

router.get('/ren', function(req, res) {
    var username = 'nik',
        password = 'abc123',
        auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

    res.redirect('http://localhost:3000/api/oauth2/authorize');
})

How can I set headers to this redirect command?

如何为此重定向命令设置标头?

回答by stavros.zavrakas

Doesn't express forward the headers automatically if you redirect with 301 (Moved Permanently) or 302 (Found)?

如果您使用 301(永久移动)或 302(已找到)重定向​​,是否不会自动转发标头?

If not, this is how you can set headers:

如果没有,您可以通过以下方式设置标题:

res.set({
  'Authorization': auth
})

or

或者

res.header('Authorization', auth)

and then call the

然后调用

res.redirect('http://localhost:3000/api/oauth2/authorize');

Finally, something like that should work:

最后,这样的事情应该有效:

router.get('/ren', function(req, res) {
    var username = 'nik',
        password = 'abc123',
    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

    res.header('Authorization', auth);

    res.redirect('http://localhost:3000/api/oauth2/authorize');
});

回答by Balthazar

As people have asked if there was any workaround about the fact headers are not properly set after a redirect, there is actually two ways you can work with:

正如人们询问是否有任何解决方法可以解决重定向后未正确设置事实标头的问题,实际上您可以使用两种方法:

First, by using a query parameter in the redirect url, which you could be extracted client-side. You could even remove it on load from the url using the history API, like showed here.

首先,通过在重定向 url 中使用查询参数,您可以在客户端提取该参数。您甚至可以在加载时使用历史 API 从 url 中删除它,如这里所示

history.pushState(null, '', location.href.split('?')[0])

Another solution would be to set a cookie before the redirect, and getting it in the client. Personally I prefer that in the sense it doesn't pollute my url in any way, I just need to remove this cookie on load with a simple helper:

另一种解决方案是在重定向之前设置一个 cookie,并将其放入客户端。就我个人而言,我更喜欢它不会以任何方式污染我的 url,我只需要使用一个简单的帮助程序在加载时删除此 cookie:

export const removeCookie = name => {
  document.cookie = `${name}=; Max-Age=0`
}

回答by Abel Osorio

I haven't tried this solution myself, but I think it worth the shot.

我自己还没有尝试过这个解决方案,但我认为值得一试。

res.location(REDIRECT_URL)
res.set(HEADERS)

res.stats(302).end()

I hope it helps, Abel

我希望它有所帮助,亚伯

回答by MJ007

Why cant you try the axios library

为什么你不能尝试 axios 库

    npm install axios

and then

进而

    return new Promise((resolve, reject) => {

        axios({
            "headers" : {
                "content-type" : "application/vnd.api+json"
            },
            "method" : method,
            "url" : url,
            "data" : data
        }).then((ax_res) => {
            var obj = {
                "status" : ax_res.status,
                "data" : ax_res.data
            }
            resolve(obj)
            return(obj)
        }).catch((ax_res) => {
            var obj = {
                "status" : ax_res.response.status,
                "data" : ax_res.response.data
            }
            resolve(obj)
            return(obj)
        })

    })