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

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

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

问题

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

  1. 这是实际获取请求的搜索/页面位置
  2. import { useSearchParams } from "next/navigation";
  3. import Footer from "../components/Footers";
  4. import Header from "../components/header";
  5. import { format } from "date-fns";
  6. import InfoCard from "../components/InfoCard";
  7. import Image from "next/image";
  8. export default async function Search() {
  9. const searchParams = useSearchParams();
  10. const locations = searchParams.get("locations");
  11. const startDate = searchParams.get("startDate");
  12. const endDate = searchParams.get("endDate");
  13. const noOfGuests = searchParams.get("noOfGuests");
  14. const formatStartDate = format(new Date(startDate), "dd MMMM");
  15. const formatEndDate = format(new Date(endDate), "dd MMMM");
  16. const days = `${formatStartDate} - ${formatEndDate}`;
  17. const resultss = await fetch("https://www.jsonkeeper.com/b/YVMX", {
  18. method: 'GET',
  19. });
  20. const resultsss = await resultss.json();
  21. console.log(resultsss);
  22. return (
  23. <div>
  24. <Header
  25. placeholder={`${locations} | ${days} | ${noOfGuests} guest(s)`}
  26. />
  27. <main className="mx-3">
  28. <p className="text-xs md:text-sm mt-3">
  29. 50+ Stays {days} for {noOfGuests} guest(s)
  30. </p>
  31. <h1 className="text-lg md:text-2xl font-bold mt-2 mb-5">
  32. Stays in {locations}
  33. </h1>
  34. <div className="mb-5 mr-3">
  35. <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 ">
  36. Free Cancellation
  37. </button>
  38. <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 ">
  39. Type of place
  40. </button>
  41. <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 ">
  42. Price
  43. </button>
  44. <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 ">
  45. Dormitory
  46. </button>
  47. <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 ">
  48. More filters
  49. </button>
  50. </div>
  51. <div className=" ">
  52. {resultsss?.map(
  53. ({
  54. img,
  55. key,
  56. location,
  57. title,
  58. description,
  59. star,
  60. price,
  61. total,
  62. }) => (
  63. <InfoCard
  64. key={total}
  65. img={img}
  66. location={location}
  67. title={title}
  68. description={description}
  69. star={star}
  70. price={price}
  71. total={total}
  72. />
  73. )
  74. )}
  75. </div>
  76. </main>
  77. <Footer />
  78. </div>
  79. );
  80. }

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

英文:

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

  1. import { useSearchParams } from &quot;next/navigation&quot;;
  2. import Footer from &quot;../components/Footers&quot;;
  3. import Header from &quot;../components/header&quot;;
  4. import { format } from &quot;date-fns&quot;;
  5. import InfoCard from &quot;../components/InfoCard&quot;;
  6. import Image from &quot;next/image&quot;;
  7. // export default async function searchRes() {
  8. // };
  9. // const searchRes = async () =&gt; {
  10. // const resultss = await fetch(&quot;https://www.jsonkeeper.com/b/YVMX&quot;);
  11. // const resultsss = await resultss.json();
  12. // return resultsss;
  13. // };
  14. export default async function Search() {
  15. // const resultsss = await searchRes();
  16. const searchParams = useSearchParams();
  17. const locations = searchParams.get(&quot;locations&quot;);
  18. const startDate = searchParams.get(&quot;startDate&quot;);
  19. const endDate = searchParams.get(&quot;endDate&quot;);
  20. const noOfGuests = searchParams.get(&quot;noOfGuests&quot;);
  21. const formatStartDate = format(new Date(startDate), &quot;dd MMMM&quot;);
  22. const formatEndDate = format(new Date(endDate), &quot;dd MMMM&quot;);
  23. const days = `${formatStartDate} - ${formatEndDate}`;
  24. const resultss = await fetch(&quot;https://www.jsonkeeper.com/b/YVMX&quot;
  25. , {
  26. method: &#39;GET&#39;,
  27. // mode: &#39;no-cors&#39;,
  28. // headers: {
  29. // &quot;Access-Control-Allow-Headers&quot; : &quot;Content-Type&quot;,
  30. // &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,
  31. // &quot;Access-Control-Allow-Methods&quot;: &quot;OPTIONS,POST,GET&quot;,
  32. // },
  33. }
  34. )
  35. // .then((res)=&gt;res.json);
  36. const resultsss = await resultss.json();
  37. console.log(resultsss);
  38. // const resultsss = await resultss();
  39. // const resultsss = await searchRes();
  40. return (
  41. &lt;div&gt;
  42. &lt;Header
  43. placeholder={`${locations} | ${days} | ${noOfGuests} guest(s)`}
  44. /&gt;
  45. &lt;main className=&quot;mx-3&quot;&gt;
  46. &lt;p className=&quot;text-xs md:text-sm mt-3&quot;&gt;
  47. 50+ Stays {days} for {noOfGuests} guest(s)
  48. &lt;/p&gt;
  49. &lt;h1 className=&quot;text-lg md:text-2xl font-bold mt-2 mb-5&quot;&gt;
  50. Stays in {locations}
  51. &lt;/h1&gt;
  52. &lt;div className=&quot;mb-5 mr-3&quot;&gt;
  53. &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;
  54. Free Cancellation
  55. &lt;/button&gt;
  56. &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;
  57. Type of place
  58. &lt;/button&gt;
  59. &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;
  60. Price
  61. &lt;/button&gt;
  62. &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;
  63. Dormitory
  64. &lt;/button&gt;
  65. &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;
  66. More filters
  67. &lt;/button&gt;
  68. &lt;/div&gt;
  69. &lt;div className=&quot; &quot;&gt;
  70. {resultsss?.map(
  71. ({
  72. img,
  73. key,
  74. location,
  75. title,
  76. description,
  77. star,
  78. price,
  79. total,
  80. }) =&gt; (
  81. &lt;InfoCard
  82. key={total}
  83. img={img}
  84. location={location}
  85. title={title}
  86. description={description}
  87. star={star}
  88. price={price}
  89. total={total}
  90. /&gt;
  91. )
  92. )}
  93. &lt;/div&gt;
  94. &lt;/main&gt;
  95. &lt;Footer /&gt;
  96. &lt;/div&gt;
  97. );
  98. }
  99. // export default Search;
  100. // https://jsonkeeper.com/b/Z5I9
  101. // for indian currency https://www.jsonkeeper.com/b/YVMX
  102. // https://cors-anywhere.herokuapp.com/

Next.config

  1. const nextConfig = {};
  2. module.exports = {
  3. async headers() {
  4. return [
  5. {
  6. // matching all API routes
  7. source: &quot;/api/:path*&quot;,
  8. headers: [
  9. { key: &quot;Access-Control-Allow-Credentials&quot;, value: &quot;true&quot; },
  10. { key: &quot;Access-Control-Allow-Origin&quot;, value: &quot;*&quot; },
  11. {
  12. key: &quot;Access-Control-Allow-Methods&quot;,
  13. value: &quot;GET,OPTIONS,PATCH,DELETE,POST,PUT&quot;,
  14. },
  15. {
  16. key: &quot;Access-Control-Allow-Headers&quot;,
  17. value:
  18. &quot;X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version&quot;,
  19. },
  20. ],
  21. },
  22. ];
  23. },
  24. images: {
  25. domains: [&quot;links.papareact.com&quot;],
  26. },
  27. };
  28. 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.

  1. import LargeCard from &quot;./components/LargeCard&quot;;
  2. import MediumCard from &quot;./components/MediumCard&quot;;
  3. import SmallCard from &quot;./components/SmallCard&quot;;
  4. import Footer from &quot;./components/Footers&quot;;
  5. import Header from &quot;./components/header&quot;;
  6. export default async function Home() {
  7. const res1 = await fetch(&quot;https://www.jsonkeeper.com/b/IJK5&quot;);
  8. const res2 = await fetch(&quot;https://www.jsonkeeper.com/b/OJBH&quot;);
  9. const data1 = await res1.json();
  10. const data11 = data1;
  11. const data2 = await res2.json();
  12. const data22 = data2;
  13. return (
  14. &lt;&gt;
  15. &lt;Header /&gt;
  16. &lt;Banner /&gt;
  17. {/* SmallCardSection */}
  18. &lt;div className=&quot; max-w-7xl mx-auto mt-5 pb-5 &quot;&gt;
  19. &lt;h2 className=&quot; ml-5 text-2xl font-bold&quot;&gt;Explore Nearby&lt;/h2&gt;
  20. &lt;div className=&quot; grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 &quot;&gt;
  21. {data11?.map((item) =&gt; (
  22. &lt;SmallCard
  23. key={item.key}
  24. img={item.img}
  25. location={item.location}
  26. distance={item.distance}
  27. /&gt;
  28. ))}
  29. &lt;/div&gt;
  30. &lt;/div&gt;
  31. {/* MediumCardSection */}
  32. &lt;section className=&quot; max-w-7xl mx-auto mt-5 pb-5 &quot;&gt;
  33. &lt;h2 className=&quot; text-2xl font-bold ml-5&quot;&gt;Live Anywhere&lt;/h2&gt;
  34. &lt;div className=&quot; relative flex flex-row space-x-3 overflow-scroll scrollbar-hide pl-5&quot;&gt;
  35. {data22?.map((item) =&gt; (
  36. &lt;MediumCard img={item.img} key={item.id} title={item.title} /&gt;
  37. ))}
  38. &lt;/div&gt;
  39. &lt;/section&gt;
  40. &lt;div className=&quot;max-w-7xl mx-auto pl-5 pr-5 lg:pr-10 &quot;&gt;
  41. &lt;LargeCard
  42. title={&quot;The Greatest Outdoors&quot;}
  43. description={&quot;Wishlists curated by Airbnb.&quot;}
  44. buttonText={&quot;Get Inspired&quot;}
  45. /&gt;
  46. &lt;/div&gt;
  47. &lt;div className=&quot; &quot;&gt;
  48. &lt;Footer /&gt;
  49. &lt;/div&gt;
  50. &lt;/&gt;
  51. );
  52. }

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

答案1

得分: 1

  1. // next.config.js
  2. module.exports = {
  3. async rewrites() {
  4. return [
  5. {
  6. source: '/api/:path*',
  7. destination: 'https://www.jsonkeeper.com/:path*',
  8. }
  9. ]
  10. }
  11. };
英文:

Can you add destination key for your api domain?

  1. // next.config.js
  2. module.exports = {
  3. async rewrites() {
  4. return [
  5. {
  6. source: &#39;/api/:path*&#39;,
  7. destination: &#39;https://www.jsonkeeper.com/:path*&#39;,
  8. }
  9. ]
  10. }
  11. };

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:

确定