从 Next.js 应用获取 Strapi API 时,为什么会收到 {statusCode: 400, error: 'Bad Request', message: 'Malicious Path'}

Tur*_*nix 1 request fetch http-status-code-400 strapi next.js

当我尝试从 Strapi API 获取数据时,我从 Next.js 应用程序中获取{statusCode: 400, error: 'Bad Request', message: 'Malicious Path'}. 我的代码如下所示:

import '../styles/globals.css'
import App from "next/app"
import Head from "next/head"
import Link from 'next/link'
import { createContext } from "react";
import { fetchAPI } from "lib/api";
import { getStrapiMedia } from "lib/media"

export const GlobalContext = createContext({})

export default function MyApp({ Component, pageProps }) {
  const { global } = pageProps;
  console.log(global)
  return (
    <>
      <Head>
        <title>{getStrapiMedia(global.siteName)}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta name="description" content={getStrapiMedia(global.metaDescription)} />
        <Link rel="shortcut icon" href={getStrapiMedia(global.favicon)} />
      </Head>
      <GlobalContext.Provider value={ global }>
        <Component { ...pageProps } />
      </GlobalContext.Provider>
    </>
  )
}

// get app's properties, ctx = context
MyApp.getInitialProps = async(ctx) => {
  const appProps = await App.getInitialProps(ctx)
  const global = await fetchAPI("/global");
  return {...appProps, pageProps: { global }}
}
Run Code Online (Sandbox Code Playgroud)

以下是 api.js 和 media.js 中的函数

const API_URL = process.env.API_URL

export function getStrapiURL(path = "") {
  return `${
    API_URL || "http://localhost:1337"
  }${path}`;
}

// Helper to make GET requests to Strapi
export async function fetchAPI(path) {
  const requestUrl = getStrapiURL(path);
  const res = await fetch(requestUrl);
  const data = await res.json();
  return data;
}
Run Code Online (Sandbox Code Playgroud)

import { getStrapiURL } from "./api";

export function getStrapiMedia(media) {
  // if media = null return nothing, else return img
  if (typeof media !== "undefined") {
    if (media == null) {
      return "";
    }
    // if media starts with "/" return API_URL + img URL else return img URL
    const imageUrl = media.url.startsWith("/")
      ? getStrapiURL(media.url)
      : media.url;

    return imageUrl;
  }
}
Run Code Online (Sandbox Code Playgroud)

它看起来不像 API 的问题,因为我可以使用邮递员获取数据,但不能在我的应用程序中获取数据。获取看起来像这样API_URL/global。任何帮助,将不胜感激。你可以在这里找到完整的代码

Tur*_*nix 7

结果我正在获取 http://API_URL//global 而不是 http://API_URL/global。改变

MyApp.getInitialProps = async(ctx) => {
  const appProps = await App.getInitialProps(ctx)
  const global = await fetchAPI("/global");
  return {...appProps, pageProps: { global }}
}
Run Code Online (Sandbox Code Playgroud)

进入

MyApp.getInitialProps = async(ctx) => {
  const appProps = await App.getInitialProps(ctx)
  const global = await fetchAPI("global");
  return {...appProps, pageProps: { global }}
}
Run Code Online (Sandbox Code Playgroud)

解决了这个问题。