我在后端使用node表示,在客户端使用angular4,这给了我以下错误:
XMLHttpRequest无法加载http://localhost:4876/login/check。对预检请求的响应没有通过访问控制检查:“访问控制 - 允许 - 凭证”的值是'回复中的标题是''哪一定是真的'当请求的凭据模式为' include'时。起源' 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);
})
}
答案 0 :(得分:12)
在corsOptions中设置cors时我添加了值凭证,它的工作原理如下:
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));
}