javascript - 响应中的“Access-Control-Allow-Credentials” header 为 '',必须为 'true'

标签 javascript node.js angular ecmascript-6

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

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

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

最佳答案

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

关于javascript - 响应中的“Access-Control-Allow-Credentials” header 为 '',必须为 'true',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772830/

相关文章:

mysql - Sequelize 复合唯一约束

css - Angular - 覆盖 swimlane/ngx-datatable 的 CSS

javascript - 实时测量画线 fabric.js

javascript - 如何使用 Ramda 按值进行无点数组搜索

javascript - 新手试图从 fastcsv 返回二维数组但返回未定义

node.js - 使用 node.js 抓取需要身份验证的网站

ruby-on-rails - 保存父项时,Embeds_many 子属性不会保留

angular - Angular Material Design 数据表中的垂直线?

javascript - 模拟 window.performance.getEntriesByType

javascript - 从 JavaScript 客户端发送到 .NET 的字符串格式的 UTC 日期正在转换为 DateTime