如何解决后端access_token无法正常传递至前端fetch方法的问题?
问题根源&修复步骤
1. 后端接口逻辑混乱+响应类型错误
你的/processor接口存在两个关键问题:
- 既然用
await调用fetchAuthenticationToken,直接就能拿到Promise resolve出来的access_token,完全没必要额外加onResult回调绕弯;而且你后续.then(resp => res.send(resp))里的resp就是这个token,但之前在回调里错误设置了application/x-protobuf的响应类型,和要返回的JSON格式不匹配。 - 回调里提前操作响应头,后续再发送响应容易出现逻辑冲突,完全是多余操作。
修正后的routes.js:
router.post('/processor', async (req, res, next) => { const setup = new Setup(); // await直接获取access_token,无需额外回调 const accessToken = await setup.fetchAuthenticationToken(); // 设置正确的JSON响应类型 res.setHeader('Content-Type', 'application/json'); // 将token包装成JSON结构返回,方便前端解析 res.send({ access_token: accessToken }); });
2. 前端未正确读取fetch响应体
你前端直接把Response实例转成JSON输出,这个对象本身不是实际响应内容,必须调用response.json()(对应后端返回的JSON格式)来提取真实数据。
修正后的前端Ws.js:
fetch(onResult) { return new Promise((resolve, reject) => { const ws = endPointsURLs.VUE_NEWSWM_APP_LOCAL_HOST_3000.description + endPointsURLs.VUE_NEWSWM_APP_PATH.description + BackendWssConstants.CONST_WS_SENTINELHUB_ENGINE_PROCESSOR.description; fetch(ws, this.#requestOptions) .then(response => { // 先解析JSON格式的响应体 return response.json(); }) .then(data => { this.#msg = JSON.stringify({msg:infoTag + 'fetch:' + ws, response: data}); console.info(this.#msg); resolve(data); onResult(data); }) .catch(err => { // 别忘了捕获请求错误 reject(err); }) }); }
额外优化建议
如果不需要fetchAuthenticationToken里的onResult回调,可以直接删掉简化方法:
// setup.js简化版 fetchAuthenticationToken() { return this.#instance.post("/xx/xx/xx/xx/xx-xx/xx", this.#body, this.#config) .then(resp => { this.#access_token = resp.data.access_token; Object.assign(this.#instance.defaults, {headers: {authorization: `Bearer ${resp.data.access_token}`}}); return this.#access_token; }); }
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

