在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Express 如何設置靜態(tài)資源可跨域?

Express 如何設置靜態(tài)資源可跨域?

在前端使用 fetch 請求 express 服務的靜態(tài)資源,例如

fetch('http://localhost:4545/1.png').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  console.log( myBlob )
});

但是發(fā)現(xiàn)報錯

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');

路由是能跨域了,但是靜態(tài)資源存在跨域問題,請問如何解決?

附上貼圖,

clipboard.png

clipboard.png

clipboard.png

請求是成功的,但沒有返回( 偶爾會有 ),但是控制臺會有報錯

回答
編輯回答
抱緊我

你需要設置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 )
});
2017年8月19日 05:18
編輯回答
不討喜

打開控制臺,看響應是否有對應的頭,你程序應該是沒有設置成功

2017年1月27日 00:41
編輯回答
終相守

有個簡單的方法,使用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))
2017年4月9日 21:35