fix(部署): 补齐直连前端时的 API 反代
This commit is contained in:
@@ -20,3 +20,45 @@ test('next dev keeps watch ignored entries compatible with webpack schema', () =
|
||||
|
||||
assert.deepEqual(ignoredList, ['**/.tmp-test/**']);
|
||||
});
|
||||
|
||||
test('next config proxies API requests when the web container is exposed directly', async () => {
|
||||
const previousTarget = process.env.NEXT_API_PROXY_TARGET;
|
||||
process.env.NEXT_API_PROXY_TARGET = 'http://server:3001';
|
||||
|
||||
try {
|
||||
const rewrites = await nextConfig.rewrites();
|
||||
assert.deepEqual(rewrites, [
|
||||
{
|
||||
source: '/api/v1/:path*',
|
||||
destination: 'http://server:3001/api/v1/:path*',
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
if (previousTarget === undefined) {
|
||||
delete process.env.NEXT_API_PROXY_TARGET;
|
||||
} else {
|
||||
process.env.NEXT_API_PROXY_TARGET = previousTarget;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('next config accepts API proxy targets that already include the API prefix', async () => {
|
||||
const previousTarget = process.env.NEXT_API_PROXY_TARGET;
|
||||
process.env.NEXT_API_PROXY_TARGET = 'http://server:3001/api/v1/';
|
||||
|
||||
try {
|
||||
const rewrites = await nextConfig.rewrites();
|
||||
assert.deepEqual(rewrites, [
|
||||
{
|
||||
source: '/api/v1/:path*',
|
||||
destination: 'http://server:3001/api/v1/:path*',
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
if (previousTarget === undefined) {
|
||||
delete process.env.NEXT_API_PROXY_TARGET;
|
||||
} else {
|
||||
process.env.NEXT_API_PROXY_TARGET = previousTarget;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,8 +7,25 @@ function toIgnoredList(ignored) {
|
||||
return entries.filter((entry) => typeof entry === 'string' && entry.length > 0);
|
||||
}
|
||||
|
||||
function toApiProxyDestination(target) {
|
||||
const cleanTarget = target.trim().replace(/\/+$/, '');
|
||||
if (!cleanTarget) return null;
|
||||
const apiBase = cleanTarget.endsWith('/api/v1') ? cleanTarget : `${cleanTarget}/api/v1`;
|
||||
return `${apiBase}/:path*`;
|
||||
}
|
||||
|
||||
const nextConfig = {
|
||||
transpilePackages: ['@ftb/shared'],
|
||||
async rewrites() {
|
||||
const destination = toApiProxyDestination(process.env.NEXT_API_PROXY_TARGET || '');
|
||||
if (!destination) return [];
|
||||
return [
|
||||
{
|
||||
source: '/api/v1/:path*',
|
||||
destination,
|
||||
},
|
||||
];
|
||||
},
|
||||
webpack(config, { dev }) {
|
||||
if (dev) {
|
||||
const ignored = toIgnoredList(config.watchOptions?.ignored);
|
||||
|
||||
Reference in New Issue
Block a user