最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

尝试获取客户端代码以成功显示响应消息

网站源码admin26浏览0评论

尝试获取客户端代码以成功显示响应消息

尝试获取客户端代码以成功显示响应消息

我是 js 新手,遇到一个问题:在我现在简化的登录页面中,如果在数据库中找不到用户的电子邮件,我会尝试将响应发送回用户。在服务器端,我有:

app.post('/login', async (req, res) => {
  try {
    const email = req.body.email;
    const password = req.body.password;

    console.log('Email: ' + email);

    // Select the 'CosmeticsLawDB' database
    await new Promise((resolve, reject) => {
      connection.query('USE CosmeticsLawDB', (error, results, fields) => {
        if (error) 
        {
          // The promise is rejected if an error occurs
          reject(error);
        } 
          else 
        {
          //The promise is resolved if the database is successfully selected
          console.log('"Clients" database selected');
          resolve();
        }
      });
    });

    // Check if the user exists in the 'Clients' table
    const results = await new Promise((resolve, reject) => {
      connection.query(`SELECT * FROM Clients WHERE email = '${email}'`, function (error, results, fields) {
        if (error) 
        {
          reject(error);
        } 
          else 
        {
          console.log('The query was successful');
          resolve(results);
        }
      });
    });

    if (results.length === 0) 
    {
      console.log('User not found in the database');
      res.status(404).json({ status: 404, message: 'Your email has not been registered yet' });
    } 
      else if (results[0].password !== password) 
    {
      console.log('Incorrect password');
      res.status(401).json({ status: 401, message: 'Incorrect password' });
    } 
      else 
    {
      console.log('Login successful');
      res.status(200).json({ status: 'success', message: 'Login successful' });
    }
  } catch (error) {
    console.error('An error occurred during login:', error);
    res.status(500).json({ status: 'error', message: 'An error occurred during login' });
  }
});

以及来自客户端代码:

document.getElementById('login-form').addEventListener('submit', async (event) => {
  event.preventDefault();

  //Get the values: email and password from the login form
  var email = document.getElementById('email').value;
  var password = document.getElementById('password').value;

  //Create an object with the email and password
  var data = { email: email, password: password };

  //Send a POST request to the server with the data in JSON format
  var response = await fetch('/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });

  //Get the response status
  var incomingResponse = await JSON.parse(response.text());
  var status = incomingResponse.status;

  console.log('Status: ' + status);

  //Display a message based on the response status
  if (status === 404) 
  {
    alert('Twój adres e-mail nie został jeszcze zarejestrowany. Proszę się zarejestrować.');
  } 
    else if (status === 401) 
  {
    alert('Invalid email or password.');
  } 
    else 
  {
    alert('An error occurred. Please try again later.');
  }
});

重点在于,在浏览器中,服务器发回请求时,渲染为:

status  404
message "Your email has not been registered yet"

不太漂亮。我正在尝试获取客户端代码来向用户提供类似警报的消息,表明他们的电子邮件尚未注册。

回答如下:

在这段代码中

  //Get the response status
  var incomingResponse = await JSON.parse(response.text());
  var status = incomingResponse.status;
  ...

我无法理解它如何解析你的response.text,因为文本是通过 Promise 给出的,所以它应该是这样的

  //Get the response status
  var responseText = await response.text();
  var incomingResponse = JSON.parse(responseText);
  var status = incomingResponse.status;
  ...
发布评论

评论列表(0)

  1. 暂无评论