Access-Control-Allow-Headers到底有什么用,为什么要包含在响应中? [英] Access-Control-Allow-Headers what does it do exactly and why is it included in a response?

查看:70
本文介绍了Access-Control-Allow-Headers到底有什么用,为什么要包含在响应中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循以下路线的 express 教程:

I am following a tutorial for express with the following routes:

module.exports = function(app) {
    app.use(function(req, res, next) {
        res.header(
            "Access-Control-Allow-Headers",
            "x-access-token, Origin, Content-Type, Accept" 
        );
        next();
    });

    app.post(
        '/api/auth/signup',
        [
            verifySignUp.checkDuplicateUsernameOrEmail,
            verifySignUp.checkRolesExist
        ],
        controller.signup
    );

    app.post('/api/auth/signin', controller.signin);
};

以通俗易懂的术语讲,这些标头是做什么的,为什么将它们包含在响应中?我以为标头是作为请求的一部分设置的.

In layman's terms what do these headers do and why are they included in the response? I thought headers were set as part of a request.

我还尝试了删除标题的应用程序,并且功能正常,所以不确定其用途是什么.

I have also tried the app with the headers removed and it functions fine, so not sure what the use is.

推荐答案

每当从交叉源向服务器发出请求时(例如,您正在从域B请求在域A托管的API),通常浏览器就会阻止它们出于安全原因.要进行导航(这可能不是正确的"一词;实际上,这是唯一的方法),有一种称为 CORS (跨源资源共享)的机制,服务器必须在其中明确地说,它也希望与其他域(源)共享资源.现在,要说明",响应必须包含正确的CORS标头,即 Access-Control-Allow-Origin标头.

Whenever a request to a server is made from cross origin (say you're requesting an API hosted at Domain A from Domain B), generally the browser blocks them for security reasons. To navigate (this might not be the 'right' word; it's, in fact, the only way of doing) this, there's a mechanism called CORS (cross origin resource sharing) in which the server has to explicitly say that it wants to allow resource sharing with other domains(origins) too. Now, to 'tell' this, the response has to contain right CORS headers which is Access-Control-Allow-Origin header.

因此,以通俗易懂的方式讲,它只是一种通知浏览器的机制,嘿!看,我有意将此响应发送到另一个来源.请不要阻止它."

So in layman terms, it's just a mechanism to inform the browser, "Hey! Look, I deliberately want to send this response to another origin. Don't block it."

这么说吧.如果服务器以通配符响应:

So let's say. if the server responds with a wildcard:

 Access-Control-Allow-Origin: *, 

这意味着该资源可以被任何域访问.

This means, the resource can be accessed by any domain.

类似地,如果服务器发送

Similarly, if the server sends

Access-Control-Allow-Origin: "https://example.com"

然后,这意味着只能在"https://example.com"

Then, this means the resource can be accessed only on this particular domain which is "https://example.com"

这是我的理解.

有关更多技术细节,您可以阅读: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

For more technical details, you may read: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

这篇关于Access-Control-Allow-Headers到底有什么用,为什么要包含在响应中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆