expresscorsamp-html

Configuring amp CORS with express


I have an express app running on Firebase Functions and a static website hosted on Firebase Hosting. This static website is a AMP website with a form which makes a post to the express app. When I submit it I get these errors:

Response must contain the AMP-Access-Control-Allow-Source-Origin header

Form submission failed: Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header​​​

In my express app:

const app = express();

app.use(function (req, res, next) {
  let origin = req.header('origin').toLowerCase()
  res.set('Access-Control-Allow-Origin', origin);
  res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, 
           Content-Type, Accept');
  res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, HEAD, PUT');
  res.set('Access-Control-Allow-Credentials', 'true');
  res.set("AMP-Access-Control-Allow-Source-Origin", origin);
  next();
});

Solution

  • Aside from res.set("AMP-Access-Control-Allow-Source-Origin", origin);
    

    Try including this header as well

    header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
    

    as mentioned from the CORS in AMP guide.

    You may also check this SO post for implementation reference.