使用JavaScript调用.NET POST API获取JWT Token后无法读取值的问题
问题分析与代码修改方案
核心问题点
- 重复调用
response.json():response.json()是异步方法,且响应流只能被读取一次,两次调用会导致第二次无法获取有效数据。 - 混合使用
async/await与.then():这种写法易造成逻辑混乱,导致响应结果传递异常。 - 未处理非成功响应:当返回4xx/5xx状态码时,没有对应的错误捕获逻辑,无法定位问题。
修改方案(推荐纯async/await风格)
try { const response = await fetch("http://users:6400/api/authenticate/get_token", { method: 'POST', mode: 'cors', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: username, password: password, application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f', web_site:'WakeNC' }) }); if (!response.ok) { // 处理非2xx状态码的错误 const errorInfo = await response.json(); throw new Error(errorInfo.message || '认证请求失败'); } const authData = await response.json(); // 根据端点实际返回结构读取Token,例如authData.token或authData.access_token console.log('获取到的Token:', authData.token); return authData; } catch (error) { console.error('请求出错:', error); }
修改说明
- 移除
.then()链式调用,统一使用async/await,逻辑更清晰。 - 仅调用一次
response.json(),将解析结果存入变量,后续直接从变量读取Token。 - 新增非成功响应的处理分支,捕获并抛出错误信息,避免静默失败。
备选方案(纯.then()风格)
fetch("http://users:6400/api/authenticate/get_token", { method: 'POST', mode: 'cors', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: username, password: password, application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f', web_site:'WakeNC' }) }) .then(response => { if (!response.ok) { return response.json().then(errorData => { throw new Error(errorData.message || '认证请求失败'); }); } return response.json(); }) .then(authData => { // 根据实际返回结构读取Token console.log('获取到的Token:', authData.token); }) .catch(error => { console.error('请求出错:', error); });
额外提示
请根据.NET端点返回的实际JSON结构,调整authData.token中的字段名(例如若返回字段为access_token,则改为authData.access_token)。
内容的提问来源于stack exchange,提问作者Vasanth R
相关产品推荐
相关产品推荐

