首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >apiKey与axios

apiKey与axios
EN

Stack Overflow用户
提问于 2022-04-29 15:11:07
回答 1查看 1.6K关注 0票数 1

我正在尝试使用一个api,其中我有用户名和密码,通过这段代码,我可以获得身份验证令牌

代码语言:javascript
复制
  axios.post(this.apiUrl,
            {
                username : 'xxx',
                password : 'yyy'
            },
  
  )
  .then((respond)=>{
    this.token = respond.data.token
    console.log(this.token)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

因为我需要这个令牌来访问同一个Api中的其他路由,所以我应该在其他请求中重用它,如本例中所示。

代码语言:javascript
复制
  axios.post(this.apiUrl+(otherEndPoint),{body},
            {
              headers:{
                  "authorization":this.token
              }
            },
  
  )
  .then((respond)=>{
    r = respond.data.token
    console.log(r)
  })
  .catch((error)=>{
    console.log('errore',error)
  })

但这不管用,有人可以帮我

EN

回答 1

Stack Overflow用户

发布于 2022-04-29 15:55:47

在不了解如何设置项目的情况下,关于如何进行项目设置的要点如下:

  1. 创建axios实例(无论是使用CDN还是从项目安装的包中导入axios )
  2. 设置axios默认头。
  3. 使用axios方法getpost

代码:

代码语言:javascript
复制
// Import axios module
import axios from 'axios';

// Set default header. e.g, X-API-KEY
axios.defaults.headers['X-API-KEY'] = 'some-api-key';

// Use axios as you would normally
axios.get('http://example.com/secure-endpoint')
    .then(res => console.log(res.data))
    .catch(err => console.log(err));

就你的情况而言:

代码语言:javascript
复制
import axios from 'axios';

// ... somewhere in code
// Get api-key from server
const username = 'someUsername';
const password = 'somePassword';
axios.post('http://example.com/api/getKey', {
    username,
    password
}).then(res => {
    axios.defaults.headers['x-api-key'] = res.data.apiKey;
})
.catch(err => console.log(err));
// ...

// ... somewhere else in code
axios.get('http://example.com/secure-endpoint')
    .then(res => console.log(res.data))
    .catch(err => console.log(err));
// ...

这些只是例子。根据您的项目结构和需求进行更改。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72060067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档