javascript - 无法从 API 获取令牌 - javascript
问题描述
我有 api localhost:8072/uaa/oauth/token 在使用 Postman 调用 API 时返回下一个数据:
{
"access_token": "some value",
"token_type": "bearer",
"refresh_token": "some value",
"expires_in": 50000,
"scope": "openid",
"jti": "some value"
}
在我的 package.json 文件中,我将代理设置为http://localhost:8072:
"proxy": "http://localhost:8072"
然后在 React 应用程序中,更准确地说,在 redux-saga 中,我正在调用 API,如下所示:
const userData = new FormData();
userData.append('grant_type', 'password');
userData.append('username', 'admin');
userData.append('password', 'admin');
const response = yield fetch('/uaa/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: userData,
})
.then(res => {
console.log('RES', res);
return res
});
问题是在浏览器中我得到了这个响应:
RES
{type: "basic", url: "http://localhost:8080/uaa/oauth/token", redirected: false, status: 404, ok: false, …}
type: "basic"
url: "http://localhost:8080/uaa/oauth/token"
redirected: false
status: 404
ok: false
statusText: "Not Found"
headers: Headers {}
body: ReadableStream
bodyUsed: false
__proto__: Response
问题
为什么 url 端口是8080而不是8072?
如何在浏览器中获得响应,就像我在 Postman 中获得的响应一样?
解决方案
Body mixin 的 json() 方法接受一个 Response 流并将其读取完成。它返回一个 Promise,该 Promise 解析为将正文文本解析为 JSON 的结果。MDN
解决方案 1:将正文响应作为 JSON
如果 JSON 数据有任何错误,那么这可能不起作用。
const response = yield fetch('/uaa/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: userData,
})
.then(res => res.json())
.then(res => {
console.log('RES', res);
return res
});
添加了这个链接then(res => res.json())
解决方案 2:以文本形式给出正文响应
这适用于每种情况,但请记住数据是文本格式。
const response = yield fetch('/uaa/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: userData,
})
.then(res => res.text())
.then(res => {
console.log('RES', res);
return res
});
添加了这个链接then(res => res.text())
推荐阅读
- javascript - 日期时间显示何时我只想要日期 mvc 文本框
- postgresql - docker-compose 与 keycloak & postgres
- r - 如何在 R 中动态更改图表标题?
- sql - Big Query : LEFT OUTER JOIN 不能在没有连接两侧的字段相等的条件下使用
- c# - 如何创建屏幕截图?
- wordpress - 在 IFRAME 中嵌入 Google 表单会导致 chrome 中出现 Http 302 重定向循环,但 Firefox 可以工作
- eloquent - Laravel 查询构建器返回多个值
- laravel - 如何忽略laravel中的软删除
- angular - 尝试在声明中将大型 Angular 8 项目移动到 9 错误
- firebase - Flutter Firestore:如何检查所有文档写入是否成功完成