我的 next.js 应用程序中有一个 api 文件夹,用于某些服务器端端点:
import { NextApiRequest, NextApiResponse } from 'next'
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD', 'POST'],
origin: '*',
optionsSuccessStatus: 200,
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export default async (req, res) => {
await runMiddleware(req, res, cors)
const POSKEY = process.env.POSKEY
const PAYEE = process.env.PAYEE
const { currency, url, locale, price } = req.body
const currentUrl = url
const apiResult = await fetch(
'https://api.test.barion.com/v2/Payment/Start',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': 3495,
},
body: JSON.stringify({
PosKey: POSKEY,
PaymentType: 'Immediate',
GuestCheckout: true,
FundingSources: ['All'],
Currency: currency,
RedirectUrl: currentUrl,
CallbackUrl: currentUrl,
Locale: locale,
Transactions: [
{
Payee: PAYEE,
Total: price,
Items: [
{
Name: 'Teszt',
Description: 'Test item comment',
Quantity: 1,
Unit: 'pc',
UnitPrice: 1,
ItemTotal: 1,
SKU: 'SM-01',
},
],
},
],
}),
}
)
.then((result) => {
return result.json()
})
.catch((error) => {
console.error(error)
})
res.status(200).json({ url: apiResult.GatewayUrl })
}
当我调用端点时,在开发中它工作得很好:
但在生产中我遇到了 500 错误。 (部署到vercel)
vercel 控制台中出现错误:
[帖子] /apigateway/ 23:30:28:53 2022-06-27T21:30:28.595Z e8c57750-4647-4e7a-b62e-6221abc141ac错误错误:找不到模块'/var/task/node_modules/next/dist/server/next.js'。 请验证 package.json 是否具有有效的“main”条目 在 tryPackage (内部/模块/cjs/loader.js:321:19) 在 Function.Module._findPath (内部/modules/cjs/loader.js:534:18) 在 Function.Module._resolveFilename (内部/modules/cjs/loader.js:888:27) 在 Function.Module._load (内部/modules/cjs/loader.js:746:27) 在 Module.require (内部/modules/cjs/loader.js:974:19) 在需要时(内部/模块/cjs/helpers.js:101:18) 在 Object.5199 (/var/task/.next/server/pages/api/gateway.js:20:39) 在 webpack_require (/var/task/.next/server/webpack-api-runtime.js:25:42) 在 webpack_exec (/var/task/.next/server/pages/api/gateway.js:109:39) 在 /var/task/.next/server/pages/api/gateway.js:110:28 { 代码:'MODULE_NOT_FOUND',路径: '/var/task/node_modules/next/package.json', requestPath: 'next' } RequestId:e8c57750-4647-4e7a-b62e-6221abc141ac 错误:运行时已退出 有错误:退出状态 1 Runtime.ExitError
我应该在 next.config 文件中添加哪些其他配置才能使其正常工作,我是这个 api 的初学者。
更新: 这解决了我的问题...https://github.com/vercel/next.js/issues/34844
问题在于 .js 文件错误导入: 同样的问题在这里:https://github.com/vercel/next.js/issues/34844#issuecomment-1055628706
TLDR: 从“next”中删除导入 { NextApiRequest, NextApiResponse };