'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'

50,948

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));
    }
Share:
50,948
Akhilesh Kumar
Author by

Akhilesh Kumar

Client-Side Technology Base: HTML5, CSS3, JavaScript (ES 5, 6+), TypeScript, Web Components, Browser Extensions CSS Frameworks / Preprocessor: Twitter Bootstrap, Skeleton, Spectre, material design, Less, Sass, PostCSS JS Frameworks / Library: Angular (1.x, 2, 4, 6, 7, 8, 9), reactJS, redux, vueJS, Hyperapp, Polymer, Knockout, jQuary, Require.js, Underscore.js, Turn.js, High Chart, Am Chart, Zing Chart, Chart.js, Google chart, immutableJS Task Runner: Grunt, Gulp, Webpack App Development: Android app development, Hybrid App development, Cordova, Cordova Plugin Development, React Native, React Native Plugin Development, Ionic, Phonegap Design Paradigm: MVC, MVVC, Micro-UI, Constructor Pattern, PubSub, Flux, V+logic Server-Side Technology: Base: NodeJS, Java, JSP, php, C++, Shell Scripting, Python, Go, Apache Shindig Frameworks / Library: Express, Async, hypernova, handlebar, pug, jade, line-by-line, json-schema, Passport, Database Connectors Database: MySQL, ORACLE 10g/11g, MongoDB, PostgreSQL, Elastic-Search, noe4j, Informix Utility: Clustered Server, Load Balancer, AWS (EC2, Cloud9, S3, Lambda, Serverless), Docker, Jenkins, C-Panel, Apache, Apache Tomcat, Apache Maven. Gradle Unit/Integrated Dev Test: Mocha, chaiJS, Should, Assert, expect, Mocky, Grunt-cefe-mocha, request, Protractor, Jest Others: WordPress, Optimize-Press, HTML-email, VOS, VOS Kernel programming, VOS Media Micro-Services, Google API (Translation, GCP, Map etc.), IOT IDEs / Servers / Tools: Eclipse, Webstorm, PyCharm, Android Studio, XCode, Visual Studio Version Control Systems: Tortoise SVN Client, Git, GitHub, Bitbucket, GitLab, Git API Big-Data: Data Analysis, Data Cleansing, Data Optimization, Data Processing, Data Visualization Data Processing Tool: Sicence, PowerBI, Data-Cleaner Web Security: Website Security Analyst, Cryptography, Back-end protection Game Engine and Logic: Smart-Fox Multiplayer Game Server, Pot Logic, Game Logic, Score Management Embedded System: Raspberry pi 3, wiring-pi, Microcontroller/Raspberry Pi connection through Web-Interface SDLC worked upon: Agile Methodology, Waterfall, Build & Fix Web-App Approach: PWA, Atomic Design, MVC, MVA

Updated on May 04, 2020

Comments

  • Akhilesh Kumar
    Akhilesh Kumar about 4 years

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

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

    Where router definition is const router = require('express').Router()

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

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