在前端使用 fetch 请求 express 服务的静态资源,例如
fetch('http://localhost:4545/1.png').then(function(response) {
return response.blob();
}).then(function(myBlob) {
console.log( myBlob )
});
但是发现报错
Failed to load http://localhost:4545/1.png: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxx' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
已经是设置了各种的请求头配置
res.header( 'Access-Control-Allow-Origin', '*' );
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.header('Access-Control-Expose-Headers', 'Content-Length');
res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
路由是能跨域了,但是静态资源存在跨域问题,请问如何解决?
附上贴图,
请求是成功的,但没有返回( 偶尔会有 ),但是控制台会有报错
你需要设置fetch请求的请求头,还需要启用
mode
为cors
模式,像这样: