[英]How to HTTP proxy for Next.js API requests
我在網上嘗試了很多東西,但到目前為止沒有任何效果。
src/pages/api/proxy/[...slug].js
):import { createProxyMiddleware } from 'http-proxy-middleware';
// Create proxy instance outside of request handler function to avoid unnecessary re-creation
const apiProxy = createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
pathRewrite: { [`^/api/proxy`]: '' },
secure: false,
});
export default function (req, res) {
apiProxy(req, res, (result) => {
if (result instanceof Error) {
throw result;
}
throw new Error(`Request '${req.url}' is not proxied! We should never reach here!`);
});
};
給我這樣的錯誤:
TypeError: Object(...) is not a function
at Module../pages/api/[...slug].js (/home/user/app/client/.next/server/pages/api/[...slug].js:109:101)
at __webpack_require__ (/home/user/app/client/.next/server/pages/api/[...slug].js:23:31)
at /home/user/app/client/.next/server/pages/api/[...slug].js:91:18
at Object.<anonymous> (/home/user/app/client/.next/server/pages/api/[...slug].js:94:10)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at DevServer.handleApiRequest (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:64:181)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
at async Object.fn (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:56:492)
at async Router.execute (/home/user/app/client/node_modules/next/dist/next-server/server/router.js:23:67)
at async DevServer.run (/home/user/app/client/node_modules/next/dist/next-server/server/next-server.js:66:1042)
next.config.js
):module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:5000/:path*' // Proxy to Backend
}
]
}
}
這東西根本行不通。
next-http-proxy-middleware
):// pages/[...all].ts
...
export default (req: NextApiRequest, res: NextApiResponse) => (
isDevelopment
? httpProxyMiddleware(req, res, {
// You can use the `http-proxy` option
target: 'https://www.example.com',
// In addition, you can use the `pathRewrite` option provided by `next-http-proxy`
pathRewrite: {
'^/api/new': '/v2',
'^/api': '',
},
})
: res.status(404).send(null)
);
這東西根本沒有文檔……不知道它是如何工作的。
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require("http-proxy-middleware")
const port = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const apiPaths = {
'/api': {
target: 'http://localhost:3080',
pathRewrite: {
'^/api': '/api'
},
changeOrigin: true
}
}
const isDevelopment = process.env.NODE_ENV !== 'production'
app.prepare().then(() => {
const server = express()
if (isDevelopment) {
server.use('/api', createProxyMiddleware(apiPaths['/api']));
}
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
}).catch(err => {
console.log('Error:::::', err)
})
這在下一個應用程序中運行 express。 我需要將下一個應用程序和服務器分開。 這不是我想要的。
在 v9.5.0 版本中,next 增加了重寫,使用代理讓我們的生活更輕松。
const isDevelopment = process.env.NODE_ENV !== "production";
const rewritesConfig = isDevelopment
? [
{
source: "/cats",
destination: process.env.CATS_ENDPOINT,
},
]
: [];
module.exports = {
reactStrictMode: true,
rewrites: async () => rewritesConfig,
};
只需在next.config.js
文件中添加 rewrites async function,該文件返回包含代理的對象數組。 如果您不希望將端點設置為 env 變量,則可以將示例中的process.env.CATS_ENDPOINT
替換為任何絕對值 url。
使用next-http-proxy-middleware
您可以在 nextjs 中輕松代理 api。
首先,看看如何在nextjs中使用api。 -https://nextjs.org/docs/api-routes/api-middlewares
{yourproject_root}/pages/api/
路徑中創建一個[...all].ts
文件。[...all].ts
文件中。export default (req: NextApiRequest, res: NextApiResponse) => httpProxyMiddleware(req, res, {
// You can use the `http-proxy` option
target:'https://www.example.com',
// In addition, you can use the `pathRewrite` option provided by `next-http-proxy`
pathRewrite: {
'^/api/google':'https://google.com',
'^/api/myhome':'https://github.com/stegano'
},
});
localhost:3000/api/google
或localhost:3000/api/myhome
。實際上,您的第一次嘗試對我next@12.1.2
:
這是我的確切代碼(但與您的代碼幾乎相同):
// 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!`
);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.