首页 > 解决方案 > Fetch API 未发送 Cookie

问题描述

我已经用 Node.js 实现了一个登录系统,它在成功验证后在客户端浏览器中放置一个 cookie。此 cookie 包含稍后从数据库中获取客户端信息所需的客户端用户名,我正在尝试使用 Fetch API 请求将该 cookie 发送到我的节点服务器,然后在服务器端读取用户名,但这会返回undefined。这是我的登录系统:

var cookie_parser = require('cookie-parser');
app.use(cookie_parser('mysecretkey'));
app.post('/login', function(req, res) {
  var loginCredentials = {
    Email: req.body.email,
    Password: req.body.password,
  }
  loginCredentials.Password = hashPassword(loginCredentials.Password);
  console.log(loginCredentials);
  CheckPassword(loginCredentials, returnResult);
  // Function used by login API method to fetch password hash by email address from database
  function CheckPassword(loginCredentials, callback) {
    con.query("SELECT Password FROM Customers WHERE Email =?", loginCredentials.Email, function(err, result) {
      if (!err) {
        callback(false, result);
      } else {
        callback(true, err);
      }
    })
  }
  // Function for returning the login result
  // if login is successful, redirect user to front page
  function returnResult(error, result) {
    if (error) {
      res.send(`Database error: ${result}`);
    } else {
      if (result.length > 0 && loginCredentials.Password == result[0].Password) {
        res.cookie('user', loginCredentials.Email, {signed: true});
        res.redirect("http://localhost:3000/");
      } else {
        res.send("Login failed: incorrect email or password");
      }
    }
  }
});

然后我试图从那个cookie中读取用户名:

app.get('/getCustomerInfo', function (req, res) {
  var username = req.signedCookies.user;
  console.log(username); // prints undefined
  if (username == undefined) {
    res.send('You are not logged in. Log in to place the order');
  } else {
    con.query("SELECT FirstName, LastName, Address, Email, Phone FROM Customers WHERE Email =?", username, function(err, result) {
      if (!err) {
        console.log(result);
        res.send(result);
      } else {
        console.log(err);
      }
    });
  }
});

这是我的 Fetch API 请求:

function GetCustomerInfo() {
  fetch(`http://127.0.0.1:5000/getCustomerInfo`, {
    method: 'GET',
    credentials: 'include'
  })
      .then((response) => response.json())
      .then((response) => {
        setCustomerInfo(response);
      })
      .catch((error) => {
        console.error(error);
      });
      return (
        <div>
          <h2>
            {customerInfo}
          </h2>
        </div>
      );
}

我究竟做错了什么?任何建议将不胜感激。

标签: javascriptnode.jsauthenticationcookiesfetch-api

解决方案


推荐阅读