在尝试获取JSON数据时,在Next.js 13.4应用中出现了CORS错误。

huangapple go评论71阅读模式
英文:

Getting Cors error in next js 13.4 app when trying to fetch json data

问题

以下是您提供的代码的中文翻译部分:

这是实际获取请求的搜索/页面位置

import { useSearchParams } from "next/navigation";
import Footer from "../components/Footers";
import Header from "../components/header";

import { format } from "date-fns";
import InfoCard from "../components/InfoCard";
import Image from "next/image";

export default async function Search() {
  const searchParams = useSearchParams();
  const locations = searchParams.get("locations");
  const startDate = searchParams.get("startDate");
  const endDate = searchParams.get("endDate");
  const noOfGuests = searchParams.get("noOfGuests");
  const formatStartDate = format(new Date(startDate), "dd MMMM");
  const formatEndDate = format(new Date(endDate), "dd MMMM");
  const days = `${formatStartDate} - ${formatEndDate}`;

  const resultss = await fetch("https://www.jsonkeeper.com/b/YVMX", {
    method: 'GET',
  });

  const resultsss = await resultss.json();
  console.log(resultsss);

  return (
    <div>
      <Header
        placeholder={`${locations}  | ${days} | ${noOfGuests} guest(s)`}
      />
      <main className="mx-3">
        <p className="text-xs md:text-sm mt-3">
          50+ Stays {days} for {noOfGuests} guest(s)
        </p>
        <h1 className="text-lg  md:text-2xl  font-bold mt-2 mb-5">
          Stays in {locations}
        </h1>
        <div className="mb-5 mr-3">
          <button className="text-xs  md:text-sm rounded-full px-3 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2  ">
            Free Cancellation
          </button>
          <button className="text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   ">
            Type of place
          </button>
          <button className="text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   ">
            Price
          </button>
          <button className="text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   ">
            Dormitory
          </button>
          <button className="text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2  ">
            More filters
          </button>
        </div>
        <div className=" ">
          {resultsss?.map(
            ({
              img,
              key,
              location,
              title,
              description,
              star,
              price,
              total,
            }) => (
              <InfoCard
                key={total}
                img={img}
                location={location}
                title={title}
                description={description}
                star={star}
                price={price}
                total={total}
              />
            )
          )}
        </div>
      </main>
      <Footer />
    </div>
  );
}

希望这有助于您的学习项目!如果您有任何其他问题或需要进一步的帮助,请随时提问。

英文:

Here is the search/page where actual fetch request is situated.

import { useSearchParams } from &quot;next/navigation&quot;;
import Footer from &quot;../components/Footers&quot;;
import Header from &quot;../components/header&quot;;
import { format } from &quot;date-fns&quot;;
import InfoCard from &quot;../components/InfoCard&quot;;
import Image from &quot;next/image&quot;;
// export default async function searchRes() {
// };
// const searchRes = async () =&gt; {
//   const resultss = await fetch(&quot;https://www.jsonkeeper.com/b/YVMX&quot;);
//   const resultsss = await resultss.json();
//   return resultsss;
// };
export default async function Search() {
// const resultsss = await searchRes();
const searchParams = useSearchParams();
const locations = searchParams.get(&quot;locations&quot;);
const startDate = searchParams.get(&quot;startDate&quot;);
const endDate = searchParams.get(&quot;endDate&quot;);
const noOfGuests = searchParams.get(&quot;noOfGuests&quot;);
const formatStartDate = format(new Date(startDate), &quot;dd MMMM&quot;);
const formatEndDate = format(new Date(endDate), &quot;dd MMMM&quot;);
const days = `${formatStartDate} - ${formatEndDate}`;
const resultss = await fetch(&quot;https://www.jsonkeeper.com/b/YVMX&quot;
, {
method: &#39;GET&#39;,
// mode: &#39;no-cors&#39;,
// headers: {
//   &quot;Access-Control-Allow-Headers&quot; : &quot;Content-Type&quot;,
//   &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,
//   &quot;Access-Control-Allow-Methods&quot;: &quot;OPTIONS,POST,GET&quot;,
// },
}
)
// .then((res)=&gt;res.json);
const resultsss = await resultss.json();
console.log(resultsss);
// const resultsss = await resultss();
// const resultsss = await searchRes();
return (
&lt;div&gt;
&lt;Header
placeholder={`${locations}  | ${days} | ${noOfGuests} guest(s)`}
/&gt;
&lt;main className=&quot;mx-3&quot;&gt;
&lt;p className=&quot;text-xs md:text-sm mt-3&quot;&gt;
50+ Stays {days} for {noOfGuests} guest(s)
&lt;/p&gt;
&lt;h1 className=&quot;text-lg  md:text-2xl  font-bold mt-2 mb-5&quot;&gt;
Stays in {locations}
&lt;/h1&gt;
&lt;div className=&quot;mb-5 mr-3&quot;&gt;
&lt;button className=&quot;text-xs  md:text-sm rounded-full px-3 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2  &quot;&gt;
Free Cancellation
&lt;/button&gt;
&lt;button className=&quot;text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   &quot;&gt;
Type of place
&lt;/button&gt;
&lt;button className=&quot;text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   &quot;&gt;
Price
&lt;/button&gt;
&lt;button className=&quot;text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2   &quot;&gt;
Dormitory
&lt;/button&gt;
&lt;button className=&quot;text-xs md:text-sm rounded-full px-2 py-2 border-gray-300 border hover:shadow-md  active:bg-slate-100 mr-2 mb-2  &quot;&gt;
More filters
&lt;/button&gt;
&lt;/div&gt;
&lt;div className=&quot; &quot;&gt;
{resultsss?.map(
({
img,
key,
location,
title,
description,
star,
price,
total,
}) =&gt; (
&lt;InfoCard
key={total}
img={img}
location={location}
title={title}
description={description}
star={star}
price={price}
total={total}
/&gt;
)
)}
&lt;/div&gt;
&lt;/main&gt;
&lt;Footer /&gt;
&lt;/div&gt;
);
}
// export default Search;
// https://jsonkeeper.com/b/Z5I9
// for indian currency https://www.jsonkeeper.com/b/YVMX
// https://cors-anywhere.herokuapp.com/

Next.config

const nextConfig = {};
module.exports = {
async headers() {
return [
{
// matching all API routes
source: &quot;/api/:path*&quot;,
headers: [
{ key: &quot;Access-Control-Allow-Credentials&quot;, value: &quot;true&quot; },
{ key: &quot;Access-Control-Allow-Origin&quot;, value: &quot;*&quot; },
{
key: &quot;Access-Control-Allow-Methods&quot;,
value: &quot;GET,OPTIONS,PATCH,DELETE,POST,PUT&quot;,
},
{
key: &quot;Access-Control-Allow-Headers&quot;,
value:
&quot;X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version&quot;,
},
],
},
];
},
images: {
domains: [&quot;links.papareact.com&quot;],
},
};
nextConfig;

Everything is working fine when cors extension is enabled on chrome.
Also I am using fetch to pull data from same source in page i.. under the app and it is working very fine. see its code as well.

import LargeCard from &quot;./components/LargeCard&quot;;
import MediumCard from &quot;./components/MediumCard&quot;;
import SmallCard from &quot;./components/SmallCard&quot;;
import Footer from &quot;./components/Footers&quot;;
import Header from &quot;./components/header&quot;;
export default async function Home() {
const res1 = await fetch(&quot;https://www.jsonkeeper.com/b/IJK5&quot;);
const res2 = await fetch(&quot;https://www.jsonkeeper.com/b/OJBH&quot;);
const data1 = await res1.json();
const data11 = data1;
const data2 = await res2.json();
const data22 = data2;
return (
&lt;&gt;
&lt;Header /&gt;
&lt;Banner /&gt;
{/* SmallCardSection */}
&lt;div className=&quot;  max-w-7xl mx-auto mt-5  pb-5  &quot;&gt;
&lt;h2 className=&quot; ml-5 text-2xl font-bold&quot;&gt;Explore Nearby&lt;/h2&gt;
&lt;div className=&quot; grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4  &quot;&gt;
{data11?.map((item) =&gt; (
&lt;SmallCard
key={item.key}
img={item.img}
location={item.location}
distance={item.distance}
/&gt;
))}
&lt;/div&gt;
&lt;/div&gt;
{/* MediumCardSection */}
&lt;section className=&quot;  max-w-7xl mx-auto mt-5   pb-5  &quot;&gt;
&lt;h2 className=&quot; text-2xl font-bold ml-5&quot;&gt;Live Anywhere&lt;/h2&gt;
&lt;div className=&quot;  relative flex flex-row space-x-3 overflow-scroll scrollbar-hide pl-5&quot;&gt;
{data22?.map((item) =&gt; (
&lt;MediumCard img={item.img} key={item.id} title={item.title} /&gt;
))}
&lt;/div&gt;
&lt;/section&gt;
&lt;div className=&quot;max-w-7xl mx-auto pl-5 pr-5 lg:pr-10 &quot;&gt;
&lt;LargeCard
title={&quot;The Greatest Outdoors&quot;}
description={&quot;Wishlists curated by Airbnb.&quot;}
buttonText={&quot;Get Inspired&quot;}
/&gt;
&lt;/div&gt;
&lt;div className=&quot; &quot;&gt;
&lt;Footer /&gt;
&lt;/div&gt;
&lt;/&gt;
);
}

I am making this project for study purpose so, not having that much knowledge

答案1

得分: 1

// next.config.js
module.exports = {
    async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'https://www.jsonkeeper.com/:path*',
          }
        ]
    }
};
英文:

Can you add destination key for your api domain?

// next.config.js
module.exports = {
async rewrites() {
return [
{
source: &#39;/api/:path*&#39;,
destination: &#39;https://www.jsonkeeper.com/:path*&#39;,
}
]
}
};

huangapple
  • 本文由 发表于 2023年6月26日 19:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定