AMP Access Control Allow Source Origin header Issue

…衆ロ難τιáo~ 提交于 2019-11-26 21:00:34

问题


How can I resolve the error below;

Failed to load resource: the server responded with a status of 500 (Internal Server Error) cdn.ampproject.org/v0.js:68 Response must contain the AMP-Access-Control-Allow-Source-Origin header Yd @ cdn.ampproject.org/v0.js:68 cdn.ampproject.org/v0.js:68 Form submission failed: Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header​​​ reported

Followed all instructions at the AMP GitHub Page on CORS.

Below is a screenshot of my PHP code at the server side and error in the console of my browser;


回答1:


Please try with following code

if(!empty($_POST)){
        $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        header("Content-type: application/json");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: ". str_replace('.', '-','https://example.com') .".cdn.ampproject.org");
        header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
        header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
        header("AMP-Redirect-To: https://example.com/thankyou.amp.html");
        header("Access-Control-Expose-Headers: AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin"); 
        echo json_encode(array('successmsg'=>'data post'));
        exit;
}

Please make sure that domain url should be https

Replace https://example.com/ to your desired url




回答2:


Although OP uses PHP, I'm posting here for my javascript peeps.

For node express server, you can use amp-toolbox-cors, which provides middleware.

const express = require('express');
const ampCors = require('amp-toolbox-cors');

const app = express();

// That's it!
app.use(ampCors());
...

By default, the AMP CORS middleware will only allow requests from AMP Caches listed on https://cdn.ampproject.org/caches.json (with the addition of bing-amp.com).

All other origins will receive a 403 response.

So for localhost or dev testing, you guys will probably want to also add the following:

app.use(ampCors({
  verifyOrigin: false
}));

For those who want to take a deeper dive, here's a link to offical docs on how to comply with AMP CORS.



来源:https://stackoverflow.com/questions/46264911/amp-access-control-allow-source-origin-header-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!