我今天遇到了错误,我解决了。
我的项目是 ionic 4 和带有 typescript 的后端 express。
错误是请求的资源上不存在“Access-Control-Allow-Origin”标头。
我在 Express 中解决了。
我在请求的后端代码“标题”中附加了以下行。
this.app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
还有这些行。
const whitelist = [
'http://localhost:8000',
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100',
];
const corsOptions = {
origin: (origin: any, callback: any) => {
console.log(origin);
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
preflightContinue: true,
credentials: true,
};
// Enable preflight requests for all routes
this.app.options('*', cors(corsOptions));
我认为您的问题与这些类似。
感谢您阅读我的建议。