topfans/frontend/vite.config.js

84 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { defineConfig } from 'vite'
import https from 'node:https'
import uni from '@dcloudio/vite-plugin-uni'
/** 与 upload-signature 返回的 OSS 虚拟域名一致;换桶时请同步 */
const OSS_DEV_HOST = 'top-fans-test.oss-cn-shanghai.aliyuncs.com'
/**
* 部分环境下 Vite 内置 server.proxy 的 rewrite 对 POST 未生效OSS 仍收到路径
* /dev-oss-proxy从而 405ResourceType: Object。此处用中间件固定转发到桶根 POST /。
*/
function ossDevPostProxyPlugin() {
return {
name: 'oss-dev-post-proxy',
configureServer(server) {
server.middlewares.use((req, res, next) => {
const raw = req.url || ''
if (!raw.startsWith('/dev-oss-proxy')) {
return next()
}
if (req.method === 'OPTIONS') {
res.statusCode = 204
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
res.setHeader(
'Access-Control-Allow-Headers',
String(req.headers['access-control-request-headers'] || '*')
)
res.end()
return
}
if (req.method !== 'POST') {
res.statusCode = 405
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('OSS dev proxy only allows POST')
return
}
const hop = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailers',
'transfer-encoding',
'upgrade'
])
/** @type {import('node:http').OutgoingHttpHeaders} */
const headers = {}
for (const [k, v] of Object.entries(req.headers)) {
if (v === undefined || hop.has(k.toLowerCase())) continue
headers[k] = v
}
headers.host = OSS_DEV_HOST
const proxyReq = https.request(
{
hostname: OSS_DEV_HOST,
port: 443,
method: 'POST',
path: '/',
headers
},
(proxyRes) => {
res.writeHead(proxyRes.statusCode || 502, proxyRes.headers)
proxyRes.pipe(res)
}
)
proxyReq.on('error', (err) => {
if (!res.headersSent) {
res.statusCode = 502
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
}
res.end(err.message)
})
req.pipe(proxyReq)
})
}
}
}
export default defineConfig({
plugins: [ossDevPostProxyPlugin(), uni()]
})