【问题标题】:'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'响应中的“Access-Control-Allow-Credentials”标头为“”,必须为“真”
【发布时间】:2017-10-02 00:57:21
【问题描述】:

我正在使用节点,在后端表示,在客户端使用 angular4,这给了我以下错误:

XMLHttpRequest 无法加载 http://localhost:4876/login/check。对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据模式为“包含”时,该值必须为“真”。因此,Origin 'http://localhost:4200' 不允许访问。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

用于登录/检查的 API 如下所示:

router.get('/login/check', (req: any, res: any) => {
        let api = new ApiConnection(req, res);
        let accessCard: IAccessCard = api.getContent(Auth.ACCESS_CARD_KEY);
        if(!Auth.isValid(accessCard))
            return api.response.error();

        ChatBox.auth.isExpired(accessCard, function (err:any, isExpired: boolean) {
            if (err) return api.response.error();
            if(!isExpired) {
                api.cookie("AccessCard", accessCard);
                api.response.success(accessCard);
            }
            else {
                api.response.error();
            }
        })
    });

其中路由器定义为const router = require('express').Router()

设置header和cors的中间件如下:

export class Application {
    private app:any = express();
    constructor() {
        this.setCors();
        this.setHeaders();
    }

    public getApp():any {
        return this.app;
    }

    private setCors(){
        let whitelist = ['http://localhost:4200','http://localhost:80'];
        let corsOptions = {
            origin: (origin:any, callback:any)=>{
                if (whitelist.indexOf(origin) !== -1) {
                    callback(null, true)
                } else {
                    callback(new Error('Not allowed by CORS'))
                }
            }
        }
        this.app.use(cors(corsOptions));
    }



    private setHeaders() {
        this.app.use(function (req:any, res:any, next: any) {

            // Website you wish to allow to connect
            //res.setHeader('Access-Control-Allow-Origin', Config.WEB_APP_HOST);
            res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');

            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader('Access-Control-Allow-Credentials', true);

            // Pass to next layer of middleware
            next();
        });
    }
}

在客户端我使用 Api 如下:

public startSession(callback: (status: boolean, result: any) => void ) {
    let self: ChatBox = this;
    /**
     * @res.result: IAccessCard
     */
    this.mApiConnection.get(Api.root+'/login/check', (res: any) => {
      if (res.status == ResponseStatus.SUCCESS) {
        self.mStorage.storeAccessCard(res.result);
        self.loadAccount(res.result);
      }
      callback(res.status, res.result);
    })
  }

【问题讨论】:

  • 显示客户端代码

标签: javascript node.js angular ecmascript-6


【解决方案1】:

在 corsOptions 中设置 cors 时,我添加了 value credentials true 它的工作原理如下:

private setCors(){
        let whitelist = ['http://localhost:4200','http://localhost:80'];
        let corsOptions = {
            origin: (origin:any, callback:any)=>{
                if (whitelist.indexOf(origin) !== -1) {
                    callback(null, true)
                } else {
                    callback(new Error('Not allowed by CORS'))
                }
            },credentials: true
        }
        this.app.use(cors(corsOptions));
    }

【讨论】:

  • credentials: true 添加Access-Control-Allow-Credentials: true 标头,如果您使用xhr.withCredentials=true developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…,则需要该标头
  • 在Sping控制器中使用内联时,使用@CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "*", allowCredentials = "true")
猜你喜欢
  • 2019-02-08
  • 2018-12-24
  • 2021-04-04
  • 2021-04-17
  • 2015-04-14
  • 2018-01-13
  • 2021-03-12
  • 2022-11-28
相关资源
最近更新 更多