I use node, express on the backend and angular4 on the client side, which gives me the following error:
XMLHttpRequest cannot load http: // localhost: 4876 / login / check . The response to the request before the flight does not pass the access control check: the value of the "Access-Control-Allow-Credentials" header in the response is ", which should be" true "when the request credential mode" turns on. "Origin ' http: // localhost : 4200 'is therefore not allowed. The credential mode of requests initiated by XMLHttpRequest is controlled by the withCredentials attribute.
The login / verification api is entered as follows:
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 is the definition of the router const router = require('express').Router()
The middleware setup for the 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) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
}
}
On the client side, I use Api as follows:
public startSession(callback: (status: boolean, result: any) => void ) {
let self: ChatBox = this;
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);
})
}