开发环境中上传图片到 TOS 时 Vite 配置跨域

207 阅读1分钟

在开发图片上传到 TOS时,在本地需要配置一些跨域设置,不然由于浏览器安全机制会引发 ‘CORS’ 也就是跨域问题。 使用 vue + vite 实现: 在实例 TOS 实例的地方:

const client = new TOS({
proxy:{
  url: '/tos-proxy',
  needProxyParams: false,
},
// 其他配置
// yourRegion 填写 Bucket 所在地域。以华北2(北京)为例,yourRegion 填写为 cn-beijing。 
region: yourRegion, 
// 填写 endpoint 名称。 
endpoint: yourEndpoint, 
// 从 STS 服务获取的临时访问密钥(AccessKey ID 和 AccessKey Secret)。 
accessKeyId: yourAccessKey, 
accessKeySecret: yourSecretKey, 
// 从 STS 服务获取的安全令牌(SecurityToken)。 
stsToken: yourSecurityToken, 
// 填写 Bucket 名称。 
bucket: yourBucket, 
});

也需要在 vite.config.ts 中进行相关配置:

{
server: {
      host: '0.0.0.0',
      hmr: true,
      port: Number.parseInt(VITE_APP_PORT, 10),
      proxy: {
           '/tos-proxy': {
              target: 'https://yourBucket.yourRegin.volces.com,
              changeOrigin: true,
              rewrite: (path) => path.replace(new RegExp(`^/tos-proxy`), ''),
            },
          }
    }
}