0

我一直在学习从 API 中提取配方信息并将其显示在页面上的编码教程。

一切都很好,直到我离开了一会儿又回来了。现在,当我将标记插入页面时,来自提取请求的图像 URL 将无法正确显示。

在控制台中,它显示整个 API 获取请求都通过并且数据在那里,但图像不会嵌入。

我收到此错误:

Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep

在此处输入图像描述

这是我正在使用的获取请求和嵌入代码:

获取代码:

export const state = {
  recipe: {},
};

export const loadRecipe = async function (id) {
  try {
    const response = await fetch(
      `https://forkify-api.herokuapp.com/api/v2/recipes/${id}`
      // `https://forkify-api.herokuapp.com/api/v2/recipes/5ed6604591c37cdc054bce57`
    );
    console.log(response);
    const data = await response.json();
    console.log(response, data);

    if (!response.ok) throw new Error(`${data.message} (${response.status})`);

    const { recipe } = data.data;

    console.log(recipe);

    state.recipe = {
      id: recipe.id,
      title: recipe.title,
      publisher: recipe.publisher,
      sourceUrl: recipe.source_url,
      servings: recipe.servings,
      image: recipe.image_url,
      cookingTime: recipe.cooking_time,
      ingredients: recipe.ingredients,
    };
    console.log(`--- this is the recipe object ---`);
    console.log(state.recipe);
  } catch (error) {
    alert(error);
  }
};

嵌入代码模块:

class RecipeView {
  #parentElement = document.querySelector('.recipe');
  #data;

  render(data) {
    this.#data = data;
    const markup = this.#generateMarkup();
    this.#clear();
    console.log(`=== image link ===`);
    console.log(this.#data.image);
    this.#parentElement.insertAdjacentHTML('afterbegin', markup);
  }
  renderSpinner() {
    const spinnerMarkup = `
      <div class="spinner">
        <svg>
          <use href="${icons}#icon-loader"></use>
        </svg>
      </div>`;
    this.#clear();
    this.#parentElement.insertAdjacentHTML('afterbegin', spinnerMarkup);
  }
  #clear() {
    this.#parentElement.innerHTML = '';
  }
  #generateMarkup() {
    return `
        <figure class="recipe__fig">
        <img src="${this.#data.image}" alt="${
      this.#data.title
    }" class="recipe__img" />
        <h1 class="recipe__title">
            <span>${this.#data.title}</span>
        </h1>
        </figure>

        <div class="recipe__details">
        <div class="recipe__info">
            <svg class="recipe__info-icon">
            <use href="${icons}#icon-clock"></use>
            </svg>
            <span class="recipe__info-data recipe__info-data--minutes">${
              this.#data.cookingTime
            }</span>
            <span class="recipe__info-text">minutes</span>
        </div>
        <div class="recipe__info">
            <svg class="recipe__info-icon">
            <use href="${icons}#icon-users"></use>
            </svg>
            <span class="recipe__info-data recipe__info-data--people">4</span>
            <span class="recipe__info-text">servings</span>

            <div class="recipe__info-buttons">
            <button class="btn--tiny btn--increase-servings">
                <svg>
                <use href="${icons}#icon-minus-circle"></use>
                </svg>
            </button>
            <button class="btn--tiny btn--increase-servings">
                <svg>
                <use href="${icons}#icon-plus-circle"></use>
                </svg>
            </button>
            </div>
        </div>

        <div class="recipe__user-generated">
            <svg>
            <use href="${icons}#icon-user"></use>
            </svg>
        </div>
        <button class="btn--round">
            <svg class="">
            <use href="${icons}#icon-bookmark-fill"></use>
            </svg>
        </button>
        </div>

        <div class="recipe__ingredients">
        <h2 class="heading--2">Recipe ingredients</h2>
        <ul class="recipe__ingredient-list">
            ${this.#data.ingredients
              .map(ing => {
                return `
            <li class="recipe__ingredient">
            <svg class="recipe__icon">
                <use href="${icons}#icon-check"></use>
            </svg>
            <div class="recipe__quantity">${ing.quantity || ''}</div>
            <div class="recipe__description">
                <span class="recipe__unit">${ing.unit}</span>
                ${ing.description}
            </div>
            </li>`;
              })
              .join('')}


            <li class="recipe__ingredient">
            <svg class="recipe__icon">
                <use href="${icons}#icon-check"></use>
            </svg>
            <div class="recipe__quantity">0.5</div>
            <div class="recipe__description">
                <span class="recipe__unit">cup</span>
                ricotta cheese
            </div>
            </li>
        </ul>
        </div>

        <div class="recipe__directions">
        <h2 class="heading--2">How to cook it</h2>
        <p class="recipe__directions-text">
            This recipe was carefully designed and tested by
            <span class="recipe__publisher">${
              this.#data.publisher
            }</span>. Please check out
            directions at their website.
        </p>
        <a
            class="btn--small recipe__btn"
            href="${this.#data.sourceUrl}"
            target="_blank"
        >
            <span>Directions</span>
            <svg class="search__icon">
            <use href="${icons}#icon-arrow-right"></use>
            </svg>
        </a>
        </div>`;
  }
}

我很感激这方面的任何帮助,因为我一直在努力解决这个问题。

4

3 回答 3

2

我现在正在做同样的教程。我只是能够通过添加 html 图像标签 crossorigin="anonymous" 来修复它。看看这是否会为您解决问题。

于 2021-06-17T18:29:00.763 回答
0

您可能有一个错误配置的响应标头。安全响应标头是 Web 服务器/应用程序在向 Web 客户端返回数据时可以设置的 HTTP 标头。它们用于传达与网站交互的 Web 浏览器的安全策略设置。您可能会在这里找到一些答案https://developer.chrome.com/docs/devtools/network/reference/#headers

于 2021-09-02T09:00:16.477 回答
0

我能够通过更新我的 loadSearchResults 函数来解决这个问题(作为一种解决方法,以便我可以继续学习),以便返回的对象引用“rec.image”而不是“rec.img_url”

export const loadSearchResults = async function(query) {
  try {
    state.search.query = query;
    const data = await getJSON(`${API_URL}?search=${query}`);
    console.log(data);

    state.search.results = data.data.recipes.map(rec => {
      return {
        id: rec.id,
        title: rec.title,
        publisher: rec.publisher,
        image: rec.image,
      };
    });
  } catch (err) {
    console.error(`${err}`);
    throw err;
  }
};

在此处输入图像描述

于 2021-06-15T01:59:42.370 回答