반응형
기본 Next.js 개발 서버를 사용하는 백엔드의 프록시
이전에는 create-react-app을 사용하여 앱을 만들 때setupProxy.js이와 유사한 API 요청을 라우팅하는 파일
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api',
proxy({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
하지만 그건 next.js에는 효과가 없는 것 같아요.같은 일을 하면 여러 가지 오류가 발생합니다.
솔루션을 검색하면 어떤 종류의 커스텀 서버를 사용하라는 말이 많습니다.그러나 기본 nextjs dev 서버를 사용하여 위와 같은 프록시를 수행하려면 어떻게 해야 합니까? (동등)npm run dev언제dev내 소포 안에.json은next dev.
이 설정에는, 이것에 관한 공식 기능이 있습니다.리라이트
통상의 패스 개서 외에, 다른 Web 서버에의 요구를 프록시 할 수도 있습니다.
next.config.js:
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:8000/:path*' // Proxy to Backend
}
]
}
}
제 설정이 도움이 되었으면 합니다.
import express from 'express';
import next from 'next';
import proxy from 'http-proxy-middleware';
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(
'/api',
proxy({
target: process.env.API_HOST,
changeOrigin: true,
}),
);
server.all('*', (req, res) => handle(req, res));
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
다음과 같습니다package.json.
"scripts": {
"dev": "NODE_ENV=development node -r esm server.js",
"build": "NODE_ENV=production next build",
"start": "NODE_ENV=production node -r esm server.js",
},
Catch-all 루트를 갖춘 다른 솔루션 +http-proxy-middleware:
// pages/api/proxy/[...slug].js
import { createProxyMiddleware } from "http-proxy-middleware"; // @2.0.6
const proxy = createProxyMiddleware({
target: process.env.BACKEND_URL,
secure: false,
pathRewrite: { "^/api/proxy": "" }, // remove `/api/proxy` prefix
});
export default function handler(req, res) {
proxy(req, res, (err) => {
if (err) {
throw err;
}
throw new Error(
`Request '${req.url}' is not proxied! We should never reach here!`
);
});
}
참조: https://stackoverflow.com/a/72310680
다시 쓰는 것은 나에게 효과가 없었고, 악리를 사용하는 것도 효과가 없었다.config.proxy.
나는 좋은 오래된 상수에 의지했다.
const SERVER_URL =
process.env.NODE_ENV === 'production' ? 'https://produrl.com : 'http://localhost:8000';
export async function getStaticProps() {
const data = axios.get(`${SERVER_URL}/api/my-route`)
// ...
}
차라리 대리 요청이나 청결을 유지하고 싶지만, 이것과 씨름할 시간이 없어요.
아마도 이 매우 간단한 설정이 다른 사람들에게 도움이 될 것이다.
언급URL : https://stackoverflow.com/questions/60925133/proxy-to-backend-with-default-next-js-dev-server
반응형
'source' 카테고리의 다른 글
| Javascript에서 PHP로 JSON 데이터를 보내시겠습니까? (0) | 2023.03.08 |
|---|---|
| 도커를 통한 MongoDB 인증 활성화 방법 (0) | 2023.03.08 |
| 필요한 경우에만 모듈을 동적으로 주입합니다. (0) | 2023.03.08 |
| expo 앱을 로드할 수 없음: 문제가 발생했습니다. (0) | 2023.03.08 |
| React 기능 컴포넌트 내에서 비동기/대기 사용 (0) | 2023.03.08 |