代码之家  ›  专栏  ›  技术社区  ›  vipin

amp list(autosuggest)错误“no cors”

  •  0
  • vipin  · 技术社区  · 6 年前

    我在用 amp自动建议 当我使用这个错误发生。我不知道怎么解决这个问题。

    api和web位于不同的域中。

    错误:

    No '**Access-Control-Allow-Origin**' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to '**no-cors**' to fetch the resource with **CORS** disabled.
    

    代码:

    <div class="suggest">
      <div
        class="autosuggest-container hidden"
        [class]="(showDropdown && query) ?
          'autosuggest-container' :
          'autosuggest-container hidden'"
      >
        <amp-list
          class="autosuggest-box"
          layout="fixed-height"
          height="120"
          src="https://myapi.com/data.json?q=xxx"
          id="autosuggest-list">
          <template type="amp-mustache">
            <amp-selector
              id="autosuggest-selector"
              keyboard-select-mode="focus"
              layout="container"
              on="
                select:
                  AMP.setState({
                    query: event.targetOption,
                    showDropdown: false
                  }),
                  autosuggest-list.hide"
            >
              {{#results}}
                <div
                  class="select-option no-outline"
                  role="option"
                  tabindex="0"
                  on="tap:autosuggest-list.hide"
                  option="{{.}}"
                >{{.}}</div>
              {{/results}}
              {{^results}}
                <div class="select-option {{#query}}empty{{/query}}">
                  {{#query}}Sorry! We don't ship to your city 😰{{/query}}
                </div>
              {{/results}}
            </amp-selector>
          </template>
        </amp-list>
      </div>
    </div>
    
    
    <amp-state id="autosuggest">
        <script type="application/json">
        {
          "endpoint": "https://myapi.com/data.json?q=xxx",
          "emptyAndInitialTemplateJson": [{
            []
          }]
        }
        </script>
      </amp-state>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   vipin    6 年前

    我通过对我的api服务器做一些小的更改来解决这个问题。

    在我的铁轨上我用 宝石架

    配置/应用程序.rb

      config.middleware.insert_before 0, "Rack::Cors" do
          allow do
            origins '*'
            resource '*', headers: :any, methods: [:get, :post, :options]
          end
        end
    

    允许cors

    response.headers['AMP-Redirect-To'] = request.protocol+request.host_with_port+url
    response.headers['Access-Control-Expose-Headers'] = 'AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin'
    response.headers['AMP-Access-Control-Allow-Source-Origin'] = params[:__amp_source_origin]