微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 express 中使用 res.render( ) 时无法呈现页面,但能够在浏览器中记录响应

如何解决在 express 中使用 res.render( ) 时无法呈现页面,但能够在浏览器中记录响应

我正在尝试使用带有 JWT 的 materialize css、vanilla js、express 和 mongoDb 构建登录系统,所以发生的事情是,我能够在服务器端生成令牌并将其发送到客户端以存储在本地存储,然后使用设置了令牌的标头再次发出获取请求(使用 fetch api 发出请求)。我将响应作为 json 返回并且可以控制台记录它,但是当我尝试呈现页面时,它不会呈现并停留在同一登录页面。我也尝试在请求调用中将内容类型设置为 text/html,但仍然无法正常工作。我在下面附上了我的代码,不胜感激。

后端代码与邮递员一起工作正常,我正在尝试创建界面。为此,我是否需要使用 fetch API 或任何其他库?

  const { data = { data: [] },status } = useQuery(
    "personsData",getPersonsInfo,{
      onSuccess: (data) => {},onError: (error) => {
        console.log(error);
      }
    }
  );
  const [doFilterFemale,setFilterFemale] = useState(false);

  const persons = doFilterFemale
    ? data.data.filter((person) => person.gender === "female")
    : data.data;

这里有一些验证

   <section id="login">
    <div class="container white z-depth-2">
        <div class="row col s12">
            <ul class="tabs blue">
                <li class="tab col s6"><a class="white-text active" href="#login-page">login</a></li>
                <li class="tab col s6"><a class="white-text" href="#signup">register</a></li>
            </ul>
            <div id="login-page" class="col s12">
                <div class="s12">
                    <form id="login-form" class="signup" autocomplete="off">
                        <h5 class="center">Login</h5>
                        <p id="message" class="center">Please login to continue</p>

                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">email</i>
                            <input type="email" id="loginEmail" onpaste="return false">
                            <label for="loginEmail">Email</label>
                            <span class="helper-text red-text login-mail right" data-error="wrong"
                                data-success="right"></span>
                        </div>


                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">lock</i>
                            <input type="password" id="loginPassword" onpaste="return false">
                            <label for="loginPassword">Password</label>
                            <span class="helper-text red-text login-password right" data-error="wrong"
                                data-success="right"></span>
                        </div>
                        <input type="submit" name="submit" value="Login"
                            class="btn col m2 offset-m5 col s4 offset-s4 blue">
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
            <div id="signup" class="col s12">
                <div class="s12">
                    <form action="" id="signup-form" class="signup" autocomplete="off">
                        <h5 class="center">Register</h5>
                        <p class="center" id="signup-msg">Don't have an account ?</p>
                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">account_circle</i>
                            <input type="text" id="username" onpaste="return false">
                            <label for="username">Username</label>
                            <span class="helper-text red-text signup-user right" data-error="wrong"
                                data-success="right"></span>
                        </div>

                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">email</i>
                            <input type="email" id="signupEmail" onpaste="return false">
                            <label for="signupEmail">Email</label>
                            <span class="helper-text red-text signup-email right" data-error="wrong"
                                data-success="right"></span>
                        </div>

                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">lock</i>
                            <input type="password" id="signupPassword" onpaste="return false">
                            <label for="signupPassword">Password</label>
                            <span class="helper-text red-text signup-password right" data-error="wrong"
                                data-success="right"></span>
                        </div>


                        <div class="input-field col m12 s12">
                            <i class="material-icons prefix">vpn_key</i>
                            <input type="password" id="signupConfirmPassword" onpaste="return false">
                            <label for="signupConfirmPassword">Confirm Password</label>
                            <span class="helper-text red-text signup-con-password right" data-error="wrong"
                                data-success="right"></span>
                        </div>

                        <input type="submit" name="submit" value="register"
                            class="btn col m2 offset-m5 col s4 offset-s4 blue">

                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

登录功能

   function loginValidate(e) {
    //after validation calling login
    login(loginEmail.value,loginPassword.value);
  }

获取个人资料

 async function login(email,password) {
    const url = "/users/login";
    const loginData = { email,password };
    const response = await fetch(url,{
        method: "POST",body: JSON.stringify(loginData),headers: {
            "Content-type": "application/json; charset=UTF-8",},});
    const data = await response.json();
    console.log(data);
    // console.log(data.token);
    // console.log(typeof data.token);
    localStorage.setItem("token",data.token);
    const localToken = localStorage.getItem("token");

    if (data.msg) {
        msg.classList.add("red-text");
        msg.innerHTML = data.msg;
    } else {
        msg.innerHTML = "Please login to continue";
        msg.classList.remove("red-text");
        loginEmail.value = "";
        loginPassword.value = "";
        getProfile(localToken);
    }
}

发送令牌的路由器

 // get profile
async function getProfile(token) {
    const url = "/users/me";
    console.log("gettting the profile.....")
    // const data = {token};
    const response = await fetch(url,{
        method: "GET",// mode: "cors",withCredentials: true,credentials: "include",// body: JSON.stringify(data),headers: {
            Authorization: "Bearer " + token,"Content-type": "application/json; charset=UTF-8",redirect: "follow",keepalive: true,});
     //even tried writing below code but didn't work as well
     // redirecting but again showing "please authenticate error"
    const data = await response.json();
    if (data._id) {
        location.assign("/dashboard");
    }
}

仪表板的用户路由器

router.post("/users/login",async (req,res) => {
try {
const user = await User.findByCredentials(
  req.body.email,req.body.password
);
const token = await user.generateAuthToken();
res.send({ user,token });
} catch (e) {
res.status(400).send({
  msg: "please provide valid credentials",});
}
});

认证文件中间件

 router.get("/users/me",auth,res) => {
   res.render("dashboard",{ user: req.user });
});

我怀疑问题出在前端,因为邮递员一切正常,我不知道我使用 fetch 发出请求的方式是否正确。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。