angular - 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);
});
});
问题是我在服务器上打印的信息是正确的,但是数据没有被发送回前端,所以我可以使用它。
解决方案
推荐阅读
- reactjs - 如何在对象数组中渲染对象
- sql - postgres:如何创建具有插入和更新访问权限的角色
- pytorch - 如何在不访问类代码的情况下加载 pytorch 模型?
- c# - c#: 使用进程开始倾斜到 Win32Exception 启动 appium 服务器
- less - PhpStorm:“执行‘少’任务”一直闪烁
- python - 这个 python 机器人不会让我运行它
- c - 使用 qsort 对 C 中的结构数组进行排序
- javascript - 我试图让我的网站在每个页面上的购物篮图标上显示购物篮中的物品数量
- amazon-web-services - 使用 cdk 列出所有 LogGroup
- java - xstream.fromXML() 调用使用新版本的 xtsream jar 返回具有空值的对象