简体   繁体   English

.env 文件访问令牌适用于 API 而不是 Next.js 中的另一个

[英].env file access token working for API but not another in Next.js

I'm calling two DBs -- WordsAPI and Spotify API.我正在调用两个数据库——WordsAPI 和 Spotify API。 For each DB there is an access token/db key, both of which I've stored in a .env file.对于每个数据库,都有一个访问令牌/db 密钥,我将它们都存储在.env文件中。

I'm fetch the data in identical ways in getStaticProps and it's working just fine for WordsAPI but not Spotify.我在getStaticProps以相同的方式获取数据,它适用于 WordsAPI 但不适用于 Spotify。 In Postman, Spotify works just fine.在 Postman 中,Spotify 工作得很好。

Here are the calls:以下是电话:

export async function getStaticProps(context) {
  const wordsRes = await fetch(
    `https://wordsapiv1.p.rapidapi.com/words/${context.params.word}/definitions`,
    {
      method: "GET",
      headers: {
        "x-rapidapi-key": process.env.NEXT_PUBLIC_DB_KEY,
        "x-rapidapi-host": "wordsapiv1.p.rapidapi.com",
      },
    }
  )
    .then((response) => {
      return response;
    })
    .catch((err) => {
      console.error(err);
    });
  const songsRes = await fetch(
    `https://api.spotify.com/v1/search?q=${context.params.word}&type=track`,
    {
      method: "GET",
      headers: {
        authorization: "Bearer " + process.env.NEXT_PUBLIC_SPOTIFY_ACCESS_TOKEN,
      },
    }
  )
    .then((response) => {
      return response;
    })
    .catch((err) => {
      console.error(err);
    });
  const wordsData = await wordsRes.json();
  const songsData = await songsRes.json();
  return {
    props: {
      wordsData,
      songsData,
    },
  };
}

the .env file is as simple as follows: .env文件很简单,如下所示:

NEXT_PUBLIC_SPOTIFY_ACCESS_TOKEN=BQDcgHT2IfAXsXXX_XXX_XXX
NEXT_PUBLIC_DB_KEY=a2c92537d6mshXXX

I heard that leaving the key at the bottom of the file without an extra line can mess it up, but switching them around didn't change anything.我听说将密钥留在文件底部而没有额外的行会弄乱它,但切换它们并没有改变任何东西。 I've also tried various combinations of switching to string format in each file, switching the header key to "authorization" , using string interpolation etc. Also tried naming my file .env.local (as was recommended for Next.js), but nothing works.我还尝试了在每个文件中切换到字符串格式的各种组合,将标题键切换为"authorization" ,使用字符串插值等。还尝试将我的文件命名为.env.local (如 Next.js 推荐的那样),但是没有任何效果。

Most of the solutions on SO seem to be about .env files not working at all, which isn't the case here. SO 上的大多数解决方案似乎都是关于 .env 文件根本不起作用,而这里的情况并非如此。

I have reviewed the code everything looks fine in general.我已经查看了代码,总体来说一切正常。 It would help if you restarted the server whenever you made a new file, I believe.我相信,如果您在制作新文件时重新启动服务器会有所帮助。 Try restating the server.尝试重新启动服务器。 It should work.它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM