如何在axios中传递头作为密钥

wsxa1bj1  于 2023-08-04  发布在  iOS
关注(0)|答案(4)|浏览(142)

我正在使用jsonbin.io,并将JSON数据托管为私有bin。我正在调用axios get请求来获取该数据。我必须在头文件中传递我的密钥
header { secret-key:mysecretkey }
但是axios不允许在header中的key作为secret-key

const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;

const fetchPhotosFlocal = async () => {
  const response = await axios.get(localUrl, {
     headers: {
        secret-key: secretKey,
     },
  });
  console.log(response);   };

字符串

secret-key在编译时出错,“secret-key”无法获取数据,现在该怎么办?

hts6caw3

hts6caw31#

secret-key在JavaScript中不是有效的标识符,因为它们不能包含连字符(有关详细信息,请参阅规范)。
在您的情况下,您可以简单地将标题的名称放在引号中,如下所示:

const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;

const fetchPhotosFlocal = async () => {
  const response = await axios.get(localUrl, {
     headers: {
        "secret-key": secretKey,
     },
  });
  console.log(response);   
};

字符串

chhkpiq4

chhkpiq42#

应该是

const fetchPhotosFlocal = async () => axios.get(localUrl, {
     headers: {
        'secret-key': secretKey,
     },
  });

const resp = await fetchPhotosFlocal();
console.log(resp);

字符串

laximzn5

laximzn53#

问题解决了,我检查了他们的文档,他们在字符串代码中传递secret_key。

req.setRequestHeader("secret-key", "<SECRET_KEY>");

字符串
这车开起来很好

const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {

const response = await axios.get(localUrl, { 
headers: {
    "secret-key": secretKey,
 },
  });
  console.log(response); };

ckx4rj1h

ckx4rj1h4#

您可以全局设置密钥。

export const baseAxios = axios.create({

  baseURL: 'http://localhost:3000',

  headers: {
    'secret-key': 'secretKey',
  },

});

字符串
然后打电话>

const fetchPhotosFlocal = async () => baseAxios.get(localUrl);
    
    const resp = await fetchPhotosFlocal();
    console.log(resp);

相关问题