1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

getServerSideProps内で、2バイト文字のパラメーター含むURLにgetしたらエラーになった

Last updated at Posted at 2021-02-04

状況

途中までuseEffectで実装してて問題はなかったのですが、SSRに変更したら2バイト文字を含むURLにgetした時だけエラーになることが分かりました

環境

 "next": {
      "version": "10.0.5"
}

ダメだった例

  const url = 
    `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/${word}`
  ;
  return axios.get(url).then(({ data }) => ({
    posts: data.posts
  }));

エラー文

Server Error
TypeError: Request path contains unescaped characters

This error happened while generating the page. Any console logs will be displayed in the terminal window.

どうやら2バイト文字はだめっぽい感じ(他の1バイト文字列のパラメーターだとこのエラーはでない)

encodeすればいけるらしい

  const url = encodeURI(   
    `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/${word}`
  );

に変更したら動きました。
やったぜ!!!!

一応全体を貼っておきます

const fetchData = async word => {
  const url = encodeURI(   
    `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/${word}`
  );
  return axios.get(url).then(({ data }) => ({
    posts: data.posts
  }));
};

export const getServerSideProps = async ({ params }) => {
  const data = await fetchData(params.word);
  return {
    props: {
      posts: data ? data.posts : []
    }
  };
};

まとめ

にわかなのでこれから色々覚える所存!!!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?