【问题标题】:Sending html page as reponse to axios call using express使用 express 发送 html 页面作为对 axios 调用的响应
【发布时间】:2019-03-07 16:26:48
【问题描述】:

我正在调用 axios 来检查现有的 JWT 令牌。如果它存在,我想呈现我的管理面板,否则重定向到登录页面。 现在我的后端是这样的:

//The admin panel page. check for valid JWT token, otherwise prompt to login page
router.use("/", (req,res)=>{
    var token = req.headers.authorization;
  if (token && token.startsWith("Bearer ")) {
    // Remove Bearer from string
    token = token.slice(7, token.length);
  }
  if (token) {
    jwt.verify(token, "secret", (err, decoded) => {
      if (err) {
        res.sendFile(path.join(__dirname , '../views/login.html'));
      } else {
        User.findOne({
          _id: decoded.id
        }).then(function (user) {
            res.sendFile(path.join(__dirname , '../views/admin.html'));
        })
      }
    });
  } else {
    res.sendFile(path.join(__dirname , '../views/login.html'));
  }
});

这工作正常,但在我的前端,我在 axios 中得到的结果是一个对象,页面没有显示,但响应存储在内存中。

Object { data: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n 

我发送的整个 html 文档都在响应的数据字段中。

这是我的 axios 调用:

function onPage(){
    if(localStorage.getItem('token')){
    const Url = "http://127.0.0.1:8000/admin/";
  const config = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": "Bearer " + localStorage.getItem('token')
    }
  };
  axios.post(Url, {}, config).then(function (response) {
      console.log(response);
    })
    .catch(error => {});
  }
  }

【问题讨论】:

    标签: javascript node.js express axios


    【解决方案1】:

    我发送的整个 html 文档都在响应的数据字段中。

    您可以通过使用the DOM 或您选择的将DOM 包装在更简单的API 中的库来做到这一点。例如,document.write(response.data) 会这样做,因为在页面的主要解析之后,document.write 会执行一个隐含的document.open,它会清除页面并将其替换为字符串。

    也就是说,如果您想进行 POST 并将页面替换为生成的完整 HTML,您可能只需要一个标准的 form 元素,因为这是它们的默认行为。

    【讨论】:

    • 我知道,问题是如何加载当前页面中的html代码数据?
    • @KristijanStefanoski - 我已经替换了答案。
    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多