首页 > 解决方案 > 如果Server以text/html类型响应,Client会识别不出来吗?

问题描述

我尝试使用 localStorage.removeItem() 函数擦除 jwt 令牌,但由于运行下面的代码而失败。

我在 Visual Studio Code 中使用 Javascript 和 Express.js 进行编码。并使用 Chrome 浏览器。

[客户]

secession = () => {
  fetch('http://localhost:3000/users/secession', {
    headers: {
      'Content-Type': 'application/json',
      'accessToken': JSON.stringify(localStorage.getItem('tokenValue')),
    }
  })
  .then((result) => {
    return result.json();
  })
  .then((data) => {
    if (data === 'success secession') {
      localStorage.removeItem('tokenValue');
      alert('Success');
    } else {
      alert('Fail. Try again');
    }
  })
  .catch((err) => err);
}

[服务器]

secession: async (req, res) => {
  try {
    const token = req.get('accessToken');
    if (typeof token !== 'undefined') {
      const decoded = jwt.verify(JSON.parse(token), secretKey);
      const result = await users.users.secession(decoded);
      // result is 'success secession' 
      res.send(result);
    } else {
      res.sendStatus(403);
    }
  } catch (err) {
    res.send(err);
  }
}

当我在服务器上将res.send(result)更改为res.json(result)时,我成功擦除了令牌。

我认为如果服务器通过 text/html发送结果,客户端不会收到响应。

但我不确定这是否正确。

标签: javascriptnode.jsexpress

解决方案


您正在向客户端发送非 JSON 的内容。有了这条线:

return result.json();

您告诉浏览器将其解析为 JSON。它不是。但是,使用以下行将引发异常:

.catch((err) => err);

你正在吞噬所有的错误。抛出它是有原因的:您正在为.json函数提供无效输入。

删除.json解析器。您可以将其替换为.text().

背景资料:

使用res.json()“修复”问题的原因是因为运行JSON.stringifysome "string" value导致"some \"string\" value",这是有效的 JSON。JSON 对象可能只是一个字符串,它不必是对象或数组。


推荐阅读