Express 如何设置静态资源可跨域?

在前端使用 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');

路由是能跨域了,但是静态资源存在跨域问题,请问如何解决?

附上贴图,

clipboard.png

clipboard.png

clipboard.png

请求是成功的,但没有返回( 偶尔会有 ),但是控制台会有报错

阅读 11.2k
4 个回答

你需要设置fetch请求的请求头,还需要启用modecors模式,像这样:

fetch('http://localhost:4545/1.png', {
    method: 'GET',
    headers: {
        'Content-Type': 'image/png'
    },
    mode: 'cors'
}).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  console.log( myBlob )
});

有个简单的方法,使用cors模块

const cors = require('cors')
app.use(cors())

npm库
github

或者

let options = {
  setHeaders: function (res, path, stat) {
    res.set('Access-Control-Allow-Origin', '*')
  }
}
app.use(express.static('public', options))

打开控制台,看响应是否有对应的头,你程序应该是没有设置成功

今天也遇到这个问题了,使用express.static后,如果要让静态资源访问可跨域,要给express.static传入第二个参数,第二项参数里有一个setHeader字段,可以设置返回的请求头
clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏