努力删除Cookie NodeJS / React

时间:2020-08-15 11:51:01

标签: javascript node.js reactjs express cookies

当我单击注销按钮时,我正在努力从浏览器中删除Cookies,在我看来该API可以正常工作,但它并未删除Cookies,并且出现了SyntaxError: Unexpected token O in JSON at position 0错误res.json();

上的浏览器端

我环顾四周,发现有多种删除Cookie的方法,但是由于Httponly标志处于启用状态,因此无法在字体末尾完成,因此我要向{{ {1}},在服务器端,我将logout=true设置为Maxage。但仍然无法正常工作。

0,但不确定在服务器端是否完全没有错误,以下是我正在I think i am doing something wrong at the server side中设置的代码

Server side

任何建议/指针都请问我在哪里做错了,从服务器端删除cookie的好方法是什么。

  • res.cookie("key", "yogaoutlet_access_token", { expires: new Date(0), domain: "localhost", path: "/" }); res.cookie("token", "", { expires: new Date(0), domain: "localhost", path: "/" }); res.redirect(200, "http://localhost:3000/") 来自前端
  • 的代码
Snippet
  • 服务器/ NodeJS / Express 附带代码段

    const delete_cookie = ( ) => {
       //setting logout=true here will ask sserver to send the cookie with maxage=0
        const dataSend = { Email: userinfo[0].email || null, password: userinfo[0].password || null, logout: true };
         
        const headers = new Headers();
        headers.append("content-type", "application/json");
    
        const options = {
          method: "POST",
          headers,
          body: JSON.stringify(dataSend),  
               credentials: "include",
        };
       
        const request = new Request("http://localhost:5000/api/newuser", options);
    
        (async () => {
          const incomingdata = await fetch(request)
            .then((res) => {
               
              if (res.status > 200 && res.status < 400) {
                // window.location.href = "http://localhost:3000/";
                
              } else {
                 
                return res.json();
               
              }
            })
            .then((body) => {
               
              return body;
            });
        })();
        // Error here SyntaxError: Unexpected token O in JSON at position 0
      };

  • 照片(来自 const cookieParser = require("cookie-parser"); const app = express(); app.use(express.json()); app.use(cookieParser()); app.use( cors({ credentials: true, // for cookies origin: "http://localhost:3000", optionsSuccessStatus: 200, }) ); app.post("/api/newuser", (req, res) => { if (req.body.logout === false) { ........................... //login cookies are sent using JWT } //if logout === true, below is the code that will work when the user click on the Logout button else{ const payload = { email: req.body.Email }; const token = jwt.sign(payload, "lllfasdgfdadsfasdfdasfcadsf"); res.setHeader("Content-Type", "application/json"); res.cookie("key", "yogaoutlet_access_token", { expires: new Date(0), domain: "localhost", path: "/" }); res.cookie("token", "", { expires: new Date(0), domain: "localhost", path: "/" }); res.redirect(200, "http://localhost:3000/");} } })

enter image description here

0 个答案:

没有答案