Reputation: 143
When I try to fetch data from strapi API, from my Next.js app I get {statusCode: 400, error: 'Bad Request', message: 'Malicious Path'}
.
My code looks like this:
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 }}
}
Here are functions from api.js and 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;
}
}
It doesn't look like a problem with API as I can fetch the data with postman but not in my App. Fetch would look like this API_URL/global
.
Any help would be appreciated.
You can find whole code here
Upvotes: 1
Views: 3764
Reputation: 143
So it turned out I was fetching http://API_URL//global instead of http://API_URL/global. Changing
MyApp.getInitialProps = async(ctx) => {
const appProps = await App.getInitialProps(ctx)
const global = await fetchAPI("/global");
return {...appProps, pageProps: { global }}
}
into
MyApp.getInitialProps = async(ctx) => {
const appProps = await App.getInitialProps(ctx)
const global = await fetchAPI("global");
return {...appProps, pageProps: { global }}
}
solved this issue.
Upvotes: 8