响应中的“Access-Control-Allow-Credentials”标题为“必须为'true' [英] 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'

查看:943
本文介绍了响应中的“Access-Control-Allow-Credentials”标题为“必须为'true'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在后端使用node,express,在客户端使用angular4,这给了我以下错误:

I'm using node, express on backend and angular4 at client side which is giving me following error:


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

XMLHttpRequest cannot load http://localhost:4876/login/check. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

登录/检查的Api如下所示:

Api for login/check is implimented as below:

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')。路由器()

为标题和焦点设置中间件如下:

Setting middleware for header and cors is as follows:

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如下:

On client side I'm using Api as follows:

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);
    })
  }


推荐答案

在corsOptions中设置cors时,我添加了值凭证,它的工作原理如下:

While setting cors in corsOptions I added value credentials true it worked as follows:

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));
    }

这篇关于响应中的“Access-Control-Allow-Credentials”标题为“必须为'true'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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