javascript 在下一个js 13.4应用程序中获取JSON数据时出现Cors错误

68bkxrlz  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(93)

这里是实际获取请求所在的搜索/页面。

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 searchRes() {

// };

// const searchRes = async () => {
//   const resultss = await fetch("https://www.jsonkeeper.com/b/YVMX");
//   const resultsss = await resultss.json();
//   return resultsss;
// };

 export default async function Search() {
  // const resultsss = await searchRes();

  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',
      // mode: 'no-cors',
      // headers: {
      //   "Access-Control-Allow-Headers" : "Content-Type",
      //   "Access-Control-Allow-Origin": "*",
      //   "Access-Control-Allow-Methods": "OPTIONS,POST,GET",
      // },
    }
    )
    // .then((res)=>res.json);

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

  // const resultsss = await resultss();
  
  

  // const resultsss = await searchRes();

  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>
  );
}

// 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: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          {
            key: "Access-Control-Allow-Methods",
            value: "GET,OPTIONS,PATCH,DELETE,POST,PUT",
          },
          {
            key: "Access-Control-Allow-Headers",
            value:
              "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version",
          },
        ],
      },
    ];
  },
  images: {
    domains: ["links.papareact.com"],
  },
};
nextConfig;

在chrome上启用cors扩展时,一切都运行得很好。此外,我正在使用fetch从页面i中的相同源中提取数据。在应用程序下,它工作得很好。也看看它的代码。

import LargeCard from "./components/LargeCard";
import MediumCard from "./components/MediumCard";
import SmallCard from "./components/SmallCard";
import Footer from "./components/Footers";

import Header from "./components/header";

export default async function Home() {
  const res1 = await fetch("https://www.jsonkeeper.com/b/IJK5");
  const res2 = await fetch("https://www.jsonkeeper.com/b/OJBH");
  const data1 = await res1.json();
  const data11 = data1;
  const data2 = await res2.json();
  const data22 = data2;

 

  return (
    <>
    
      <Header />
      <Banner />

      {/* SmallCardSection */}
      <div className="  max-w-7xl mx-auto mt-5  pb-5  ">
        <h2 className=" ml-5 text-2xl font-bold">Explore Nearby</h2>
        <div className=" grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4  ">
          {data11?.map((item) => (
            <SmallCard
              key={item.key}
              img={item.img}
              location={item.location}
              distance={item.distance}
            />
          ))}
        </div>
      </div>
      {/* MediumCardSection */}
      <section className="  max-w-7xl mx-auto mt-5   pb-5  ">
        <h2 className=" text-2xl font-bold ml-5">Live Anywhere</h2>
        <div className="  relative flex flex-row space-x-3 overflow-scroll scrollbar-hide pl-5">
          {data22?.map((item) => (
            <MediumCard img={item.img} key={item.id} title={item.title} />
          ))}
        </div>
      </section>
      <div className="max-w-7xl mx-auto pl-5 pr-5 lg:pr-10 ">
        <LargeCard
          title={"The Greatest Outdoors"}
          description={"Wishlists curated by Airbnb."}
          buttonText={"Get Inspired"}
        />
      </div>
      <div className=" ">
        <Footer />
      </div>
    </>
  );
}

我做这个项目的学习目的,所以,没有那么多的知识

eyh26e7m

eyh26e7m1#

你能为你的API域添加目标键吗?

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

相关问题