CodeGenieApp / CodeGenieApp/serverless-express

How to enable CORS programmatically on serverless express?

Đang mở
#384 1 bình luận 0 reaction 1 người được giao Xem trên GitHub

@brett-vendia đang làm issue này rồi.

Từ ngày 10/3/2021.

question
Ngôn ngữ chính
JavaScript
Star
5.3k
Fork
674
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

I hope it is the right repository for asking this question.

I have a aws amplify project and defined a REST API index.js like this:

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

Based on this documentation if I want to activate the CORS I have to apply this changes:

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

However, in the newest version of AWS cli it generates the expirts.handler like the first snippet of code by using serverless express; and it places the following code in app.js:

// Enable CORS for all methods
server.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "OPTIONS,POST,GET");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

Unfortunately this code does not activate the CORS on my API.

My question is, how can I add headers to aws-serverless-express?

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.