错误:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

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

我制作了一个应用程序,我使用无服务器 AWS 托管它...我是 AWS 新手,我不知道为什么会收到此错误:“已被 CORS 策略阻止:没有‘Access-Control-Allow-Origin’ ' 标头存在于请求的资源上。”...当我使用命令 sls离线在本地运行后端时,它在我的 localhost:4000 上运行良好...但是当我尝试使用我部署的后端时,它不起作用。 .

我的后端在 Nest.js 中,前端在 Next.js 中,使用 typescript。

这是我的 serverles.ts 文件:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';
import serverlessExpress from '@vendia/serverless-express';
import { Callback, Context, Handler } from 'aws-lambda';

let server: Handler;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const cors = require('cors');
  app.use(
    cors({
      origin: 'http://localhost:3000', // Allow your frontend server
      credentials: true, // Allow credentials (cookies) to be sent with requests
    }),
  );

  await app.init();

  const expressApp = app.getHttpAdapter().getInstance();
  return serverlessExpress({ app: expressApp });
}

export const handler: Handler = async (
  event: any,
  context: Context,
  calback: Callback,
) => {
  server = server ?? (await bootstrap());
  return server(event, context, calback);
};

这是我的 serverless.yaml :

service: <value>

useDotenv: true

plugins:
  - serverless-offline
  - serverless-plugin-common-excludes 
  - serverless-plugin-include-dependencies

provider:
  name: aws
  runtime: nodejs18.x
  region: eu-west-1
  memorySize: 1024
  stage: ${opt:stage, 'dev'}
  httpApi:
    cors: true
    
  environment:
    JWT_SECRET: ${env:JWT_SECRET}
    JWT_EXPIRE: ${env:JWT_EXPIRE}

    DB_URI: ${env:DB_URI}

    TZ: ${env:TZ}

    AWS_S3_REGION: ${env:AWS_S3_REGION}

    UPLOAD_RATE_TTL: ${env:UPLOAD_RATE_TTL}
    UPLOAD_RATE_LIMIT: ${env:UPLOAD_RATE_LIMIT}

functions:
  main:
    handler: dist/serverless.handler
    timeout: 30
    role: <value>
    events:
      - http:
          path: /
          method: ANY
          cors: true
      - http:
          path: "{proxy+}"
          method: ANY
          cors: true
custom:
 serverless-offline:
   httpPort: 4000

我还在我的 aws 控制台中启用了 cors,如下图所示:

amazon-web-services amazon-s3 aws-lambda cors serverless
1个回答
0
投票

我找到了解决办法,其实很简单。我所要做的就是在我的处理程序中手动添加标头

  const response = await server(event, context, callback);

  // Add CORS headers to the response
  response.headers = {
    ...response.headers,
    'Access-Control-Allow-Origin': '*', // Replace with your frontend domain
    'Access-Control-Allow-Credentials': 'true',
  };
© www.soinside.com 2019 - 2024. All rights reserved.