首页 > 解决方案 > 无法从 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 中获得的响应一样?

标签: javascriptreactjsfetch

解决方案


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())


推荐阅读