首页 > 解决方案 > HttpClient 对 Axios 的请求

问题描述

我是前端和后端的新手,我需要使用不属于我的 API 发出一些身份验证请求,我坚信只使用 Angular 前端是可能的,但我碰巧我提出的每个请求都收到了 CORS POLICY 错误,所以我做了更多的研究,我找到了一种避免这种情况的方法,“制作后端”并使用 axios 向 API 发出请求。

所以 tis 是我从 Angular 前端调用的方法

CallBitlyServiceGetAccessToken() {
   const res = this._bitlyApiService.GetAccessToken(this.clientId, this.clientSecret).then(res => 
   console.log(res));
  }

这是另一个类中的方法。

  const endpoint = axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    'content-type': 'aplication/json',
  }
});

  GetAccessToken(ClientId: string, ClientSecret: string) {
    return endpoint.post('/access_token', {ClientId, ClientSecret}).then(res => {
      console.log('hola' + res);
      return res;
    });
  }

这是后端的方法。

app.post('/access_token', function(req, res) {
    const basicAuth = new Buffer(`${req.body.ClientId}:${req.body.ClientSecret}`);
    const options = {
        method: 'post',
        headers: {
            'Authorization': 'Basic ' + basicAuth.toString('base64'),
        },
        url: `https://api-ssl.bitly.com/oauth/access_token`,
    };
    axios(options).then(token => {
        console.log(token.data);
        res.send(token.data);
    });
});

问题是我在服务器上打印的信息是正确的,但是数据没有被发送回前端,所以我可以使用它。

标签: angularaxiosfrontendhttpclient

解决方案


推荐阅读