在将我的 NextJS 14 应用程序部署到生产环境并检查中间件中的 CORS 白名单后,AWS Amplify 充当 localhost:3000

问题描述 投票:0回答:1

使用 GitHub 将我的 NextJS (14.2.20) 应用程序部署到 AWS Amplify 后,服务器端的源应该是所述应用程序的域,以便我可以检查 CORS。 例如:

https://main.xxxxxx.amplifyapp.com
但原点是:
https://localhost:3000

请注意,当我将其部署到 Vercel 时,这个问题永远不会发生,并且即使我的本地源有不同的端口(http://localhost:88888),它也可以在本地工作。所以我猜测 AWS 配置有问题或者缺少配置。

以下是我在

middleware.ts
中检查 CORS 白名单的方法:

export const middleware = async (req: NextRequest) => {
const origin = req.nextUrl.origin;

if (!publicEnv.CORS_WHITELIST?.includes(origin)) {
 return NextResponse.json({ error: `Access denied. Environment: ${process.env.NODE_ENV}. Your Origin: ${origin} | Whitelist: ${publicEnv.CORS_WHITELIST}` }, { status: 405 })
}
...

这是部署的结果:

{"error":"Access denied. Environment: production. Your Origin: https://localhost:3000 | Whitelist: https://main.xxxxxx.amplifyapp.com"}

如果需要,这里有更多信息。

amplify.yml
文件内:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci --cache .npm --prefer-offline
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - .npm/**/*
      - node_modules/**/*

此外,无论

customHttp.yml
文件是否为或具有此内容,它仍然不起作用,我已经测试了这两种情况:

customHeaders:
  - pattern: "**/*"
    headers:
      - key: Access-Control-Allow-Origin
        value: https://main.xxxxxx.amplifyapp.com
      - key: Access-Control-Allow-Headers
        value: Origin, X-Requested-With, Content-Type, Accept, Authorization
      - key: Access-Control-Allow-Methods
        value: GET, POST, PUT, PATCH, DELETE, OPTIONS

对于package.json文件中的

scripts
,我也尝试过这两种方案。

第一个场景:

"scripts": {
    "dev": "next dev -p 88888",
    "build": "next build",
    "start": "next start -p 88888",
    "lint": "next lint"
}

第二种情况:

"scripts": {
    "dev": "next dev -p 88888",
    "build": "NODE_ENV=production next build",
    "start": "NODE_ENV=production next start",
    "lint": "next lint"
}

从结果中可以看到,它被标记为 product 并且仍然使用 localhost 作为源。

amazon-web-services deployment aws-amplify nextjs14
1个回答
0
投票

我已经找到问题所在了。而不是:

export const middleware = async (req: NextRequest) => {
const origin = req.nextUrl.origin;

if (!publicEnv.CORS_WHITELIST?.includes(origin)) {
 return NextResponse.json({ error: `Access denied. Environment: ${process.env.NODE_ENV}. Your Origin: ${origin} | Whitelist: ${publicEnv.CORS_WHITELIST}` }, { status: 405 })
}
...

我已经完成了:

export const middleware = async (req: NextRequest) => {
const host = req.headers.get("host");
    const protocol = process.env.NODE_ENV === "production" ? "https" : "http";
    const origin = `${protocol}://${host}`;

    if (!origin || !publicEnv.CORS_WHITELIST?.includes(origin)) {
        return NextResponse.json({ error: `Access denied. Environment: ${process.env.NODE_ENV}. Your Origin: ${origin} | Whitelist: ${publicEnv.CORS_WHITELIST}` }, { status: 405 })
    }
...

还有谁在第一次发布时无缘无故地否决了该帖子?哈哈。

© www.soinside.com 2019 - 2024. All rights reserved.