Why am I getting {statusCode: 400, error: 'Bad Request', message: 'Malicious Path'} when fetching strapi API from my Next.js app

Why am I getting {statusCode: 400, error: 'Bad Request', message: 'Malicious Path'} when fetching strapi API from my Next.js app

当我尝试从我的 Next.js 应用中的 strapi API 获取数据时,我得到了 {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 }}
}

这里是 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;
}

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

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

原来我是在获取 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 }}
}

进入

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

解决了这个问题。