跨域问题的背景

解决跨域加载图片资源的方法

方法一:使用Webpack配置

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        type: 'asset/resource',
        generator: {
          filename: 'images/[hash:8][name].[ext]'
        }
      }
    ]
  }
  // ...
};

方法二:使用Base64编码

methods: {
  getImageBase64(image) {
    return `data:image/jpeg;base64,${image}`;
  }
}

方法三:使用代理服务器

在开发环境中,可以通过配置代理服务器来绕过跨域限制。Vue CLI提供了代理配置,可以轻松实现。

module.exports = {
  // ...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://example.com',
        changeOrigin: true,
        pathRewrite: { '^/api': '' }
      }
    }
  }
  // ...
};

方法四:使用CORS头部

Access-Control-Allow-Origin: *

方法五:使用Nginx反向代理

如果服务器使用Nginx,可以通过配置反向代理来解决跨域问题。

server {
  location /images/ {
    proxy_pass http://example.com/;
    add_header 'Access-Control-Allow-Origin' '*';
  }
}

总结