首页 > 解决方案 > 我的基于 axios 的前端服务器无法收到来自后端服务器的任何响应

问题描述

我一直在创建一个具有前端和后端功能的响应式电影网站。我还创建了一个 mysql 数据库,其中包含我想在前端显示的电影数据。

我目前正在使用 axios 来处理 http 请求。我已经设计了我的前端和后端服务器,并且刚刚开始实施 axios 来帮助将数据从我的 mysql 服务器获取到我的前端 html。

但是,每当我尝试运行两台服务器并转到 localhost:3001/movies 时,它都会显示来自 mysql 数据库的数据。它将给出一个请求失败,状态码为 404。

这是我检查页面时收到的错误消息

 <!DOCTYPE html>
<html lang="en">

<style>
  .big-banner{
    height: 100vh;
    min-height: 500px;
    background-image: url(homeBackground.png);
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }
  
  
  /* ----------------- Styles for page 1: Home Page --------------------*/
  
  div#aboutCyber {
      margin-bottom: 6%;
  }
  
  
  
  div#aboutCyber {
      text-align: center;
      max-width: 65%;
      padding-top: 0%;
      
  }
  
  div#aboutCyber > h3 {
      font-size: 2.2em;
      font-weight: bold;
      text-align: center;
      
  }
  
  div#aboutCyber > p{
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      font-size: 1.5em;
      font-weight: 350;
      margin-top: 2%;
  }
  
  
  div#aboutCybersecurityImg > img {
      margin-left: 20%;
  }
  
  
  div#cyberattackGallery {
      background-color: rgb(237, 240, 243);
  }
  
  
  div#cyberattackExamples {
      margin-top: 9%;
      padding: 50px 0;
  }
  
  div#cyberattackExamples > h3 {
      text-align: center;
  }
  
  
  section#reasonsWhy {
          padding: 130px 0;
  }
  
  section#reasonsWhy h2 {
    text-align: center;
  }
  
  
  
  
  div#reasonsWhyHeading > h2{
      text-align: center;
  }
  
  
  section#websitePurpose {
      text-align: center;
  
  }
  
  
  div.purposes {
      padding: 60px;
  }
  
  
  section#contactSection {
    padding: 100px 0;
    text-align: center;
  }
  
</style>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="About Cybersecurity home page">
    <meta name="keywords" content="Cybersecurity, services, cybersecurity services">
    <title>movies Page</title>
     <!-- Latest compiled and minified CSS -->
     <link rel ="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

     <!-- jQuery library -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

     <!-- Popper JS -->
     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

     <!-- Latest compiled JavaScript -->
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

     <!--Font-awesome link-->
     <link rel ="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">


     <link  href="/spmoviesFrontend/public/styles.css">

     <!-- <script src="javascriptCodes.js"></script> -->


     
     
<body>
 
   <!--------------------- Navigation -------------------------------->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="mainNav">
    <div class="container">
      <a class="navbar-brand js-scroll-trigger" href="#page-top">All about Cybersecurity</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="home.html">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="cyberthreats.html">Cyberthreats</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="communities.html">Communities</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="badHabits.html">Bad Internet Habits</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="cyb">Cybersecurity services</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

<!------------------------------Background img-------------------------->


<header class="big-banner">
  <div class="container h-100 text-light">
    <div class="row h-100 align-items-center">
      <div class="col-12 text-center">
        <div class="col-md-12 mb-4 white-text text-center wow fadeIn">

          <h3 class="display-3  white-text mb-0 pt-md-5 pt-5">Cybersecurity</h3>
          <hr class="hr-light my-4 w-75">
          <h3 class="subtext-header mt-2 mb-4 ">Why you should pay attention to it</h3>
        </div>
      </div>
    </div>
  </div>
</header>


<!---------------------------Opening tag line and description----------------------->  

    <div class="jumbotron jumbotron-fluid bg-white" id="aboutCyberJumbo">
      <div class="container" id="aboutCyber">
        <h2>Welcome</h2>     
        <p>All your cybersecurity needs and inquiries on one website!</p>
      </div>
    </div>


<!------------------------------About Cyber-security-------------------------->  
<div class="container my-5">


  <!-- Section: Block Content -->
  <section class="dark-grey-text">

    <h3 class="text-center font-weight-bold mb-4 pb-2">About Cybersecurity</h3>
    <p class="text-center text-muted w-responsive mx-auto mb-5">Cybersecurity, computer security, IT security. However you call it, they all mean the same thing. It is the practise of defending computers, mobile devices, networks and data from malicious attacks. Such attacks are commonly referred to as cyber-threats. There are many reasons why an attack was launched, but the most common reason is to access and steal sensitive data from a company's archives to a person's personal computer.</p>
   
      <!-- Grid column -->
     
        <!-- Grid column -->

    </div>
    <!-- Grid row -->

    <hr class="my-5"> 

  </section>
  <!-- Section: Block Content -->


</div>

<div id="posts">


</div>
    
<!-- <div id="posts">
  <div class="card" style="margin-top: 2rem;">
      <div class="card-body">
          <p class="card-text">Hello!</p>
      </div>
      <div class="card-footer text-muted">
          10 July 2019
      </div>
  </div>
  <div class="card" style="margin-top: 2rem;">
      <div class="card-body">
          <p class="card-text">Hello World!</p>
      </div>
      <div class="card-footer text-muted">
          10 July 2019
      </div>
  </div>
</div> -->




<!-------------------Examples of cyberattacks and cyber attack statistics--------------->  

<div class="container-fluid bg-light">

  <div class="container" id="cyberattackExamples">
      
    <h3 class="my-4">Cyberthreats can target anyone </h3>
    <hr class="mt-4 mb-4">
    <div class="row">
        <div class="col-lg-6 mb-4 ">
          <div class="card h-100 shadow">
            <a href="#"><img class="card-img-top" src="images_page1/equifaxBreach.png" alt=""></a>
            <div class="card-body">
              <h4 class="card-title">
                <a href="#">Equifax data breach</a>
              </h4>
              <p class="card-text">Equifax suffered a massive data breach in 2017, which resulted in millions of customer records being compromised</p>
            </div>
            <a href='https://www.csoonline.com/article/3444488/equifax-data-breach-faq-what-happened-who-was-affected-what-was-the-impact.html'><button type="button" class="btn btn-primary btn-rounded">Read More</button>
          </div>
        </div>

        <div class="col-lg-6 mb-4">
          <div class="card h-100 shadow">
            <a href="#"><img class="card-img-top" src="images_page1/facebookBreach.png" alt=""></a>
            <div class="card-body">
              <h4 class="card-title">
                <a href="#">Facebook's security breach</a>
              </h4>
              <p class="card-text">In 2018, Facebook suffered from a cyberattack, which resulted in the privacy of 50 million user accounts being affected being compromised </p>
            </div>
            <a href="https://www.wired.com/story/facebook-security-breach-50-million-accounts/"><button type="button" class="btn btn-primary btn-rounded">Read more</button></a>
          </div>
        </div>
    


    <div class="container" id="cyberattackExamples">
            <!-- Page Heading -->
            <h3 class="my-4">Just because you are a teenager doesn't mean you are invulnerable</h3>
          <hr class="mt-4 mb-4">

        <div class="row">
          <div class="col-lg-6 mb-4">
            <div class="card h-100 shadow">
              <a href="#"><img class="card-img-top" src="images_page1/businessInsider.png" alt=""></a>
              <div class="card-body">
                <h4 class="card-title">
                  <a href="#">BusinessInsider report</a>
                </h4>
                <p class="card-text">A report published by research firm Software Advice found out that Millenials are the most apatheic when it comes to safety precautions online. it found that Millenials were most likely to do things that affect their security online such as reusing their passwords.</p>
              </div>
              <a href="https://www.businessinsider.com/millennials-are-most-vulnerable-to-hacks-2015-5"><button type="button" class="btn btn-primary btn-rounded">Read more</button></a>
            </div>
          </div>
          <div class="col-lg-6 mb-4">
            <div class="card h-100 shadow">
              <a href="#"><img class="card-img-top" src="images_page1/whichUKreport.png" alt=""></a>
              <div class="card-body">
                <h4 class="card-title">
                  <a href="#">Which? report on the scams targetting young people</a>
                </h4>
                <p class="card-text"> The article talked about how scams such as job scams and social media scams commonly affect young people and why they are being affected the most.</p>
              </div>
              <a href="https://www.which.co.uk/news/2018/06/five-scams-that-target-young-people-and-what-if-could-mean-for-their-future/"><button type="button" class="btn btn-primary btn-rounded">Read more</button></a>
            </div>
          </div>
        </div>
      </div>       
    </div>
  </div>
</div>


<!--------------------------Why should you care about Cybersecurity, section----------------------->  

  <section id="reasonsWhy">
    <div class="container">
      <div class="row">
        <div>
            <h2>So why should you care about Cybersecurity ?</h2>
            <hr>
              <p class="lead">For individuals, cybersecurity is important to everyone as it is the practice of protecting your computer, smartphones or any other digital device against malicious attacks. Without cybersecurity, you face the risk of being the victim of a multitude of cyberthreats. Being the victim of a cyberthreat is.............less than ideal, to put it nicely</p>
              <p class="lead">Without cybersecurity, you run the risk of:</p>
              
              <div class="list-group">
                <a class="list-group-item list-group-item-action flex-column align-items-start ">
                  <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">Having sensitive data stolen</h5>
                  </div>
                
                

                <a class="list-group-item list-group-item-action flex-column align-items-start">
                  <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">Having your computer infected by malicious software</h5>
                  </div>
                  

                <a class="list-group-item list-group-item-action flex-column align-items-start">
                  <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">Falling for cyber scams</h5>
                  </div>
                 
                </a>
              </div>
              <p class="lead">And the list goes on.</p>
              <p class="lead">As you can see, being the victim of a cyberthreat such as hacking or malware has potentially devastating consequences. In addition, awareness of cyber scams is also key to protecting yourself from harm when using your computer or the Internet.</p>
          </div>
        </div>
      </div>
    </div>
  </section>

<!---------------------------WHat the user can do on the website----------------------->  

<section id="websitePurpose">
  <div class="container-fluid bg-light">
    <div class="row">
      <div class="purposes">
          <div class="col-lg-8 mx-auto">
            <h2>So........ how does this website help me to learn more about cybersecurity as a whole ?</h2>
            <hr>
            <p class="lead">Well then my friend, you are in luck as you have come to the right place to learn all about cybersecurity, cyberthreats, services and more ! </p>
            <p>You may be wondering what this website does differently to help you learn about this issue. Well for starters, I have compiled a collection of the most common forms of cyberthreats and malware that befall on teens and young adults, a brief explanation on how they work and the ways you can prevent yourself from being a victim of such threats.</p>
          </div>
        </div>
    </div>
    <div class="row">
      <div class="purposes">
          <div class="col-lg-8 mx-auto">
            <h2>The ins and outs of cybersecurity isn't as complicated as you think</h2>
            <hr>
            <p class="lead">Don't think I'd forgotten about your bad Internet habits just yet</p>
            <p>C'mon, we've all done it before. Clicking on “Agree” without reading the terms. Doing a little online shopping while using free public WiFi. Downloading files from dubious websites. And, of course, creating easy-to-guess passwords, because “no one is interested in hacking my accounts.” Don’t worry. You’re not alone. Even I've had some of these habits before. Using a simple password ? Guilty as charged. However, these bad Internet habits are a lot more unsafe than you think. Which is why I have also complied a list of the common bad Internet usage and computer habits that you might have, why you should break them, and how some of them could bite you back in the long run should you not break them. </p>
          </div>
        </div>
    </div>

    <div class="row">
      <div class="purposes">
          <div class="col-lg-8 mx-auto">
            <h2>The cybersecurity communities to join and newsletters to subscribe to are endless</h2>
            <hr>
            <p class="lead">If you are keen on the issue of cybersecurity and wish to know more about it, you can join on of the many different communities out there dedicated to the issue. These communities consist of forums where you can ask questions regarding cybersecurity to newsletters and magazines which publish the latest news stories such as cyber attacks and developments in anti-virus and malware.</p>
          </div>
      </div>
    </div>
    <div class="row">
      <div class="purposes">
          <div class="col-lg-8 mx-auto">
            <h2>There are a vast array of services out there for you if you are interested</h2>
            <hr>
            <p class="lead">Cybersecurity services, anti-virus software, communities, the resources out there are endless.</p>
            <p>Last but not least, this website also contains a page dedicated to providing you with information about the different cybersecurity services out there as well as the different communities you can join or newsletters to subscribe to if you would like to know more about cybersecurity related issues. For example, I would be providing a short recommendation of the anti-virus software i think is best for you and why that is so.</p>
          </div>
      </div>
    </div>

    
  </div>
</section>



<section id="contactSection">
  <div class="container-fluid">
      <div class="row">
        <div class="col-lg-8 mx-auto">
          <h2>Get In Touch !</h2>
          <hr>
          <p class="lead">Do you still have any burning questions ? Inquiries ? Or have any feedback regarding my website.</p>
          <p class="lead">Well, if it is the latter, then I would like to give you my thanks in advance for helping me improve this website at every step ! Just leave your email and phone number below, as well as a message if you have anything in particular to say, and I will get to you as soon as I can !</p>
        </div>
      </div>
  </div>
</section>

<section id="formSection">
    <div class="container">
      <form id="feedback" action="#" method="post" onsubmit="return validateForm()">
        <fieldset id="userInfo">
        <!------------------------First and Last name--------------------->
          <div class="form-row">
            <div class="col">
              <input name="userFirstName" type="text" class="form-control" placeholder="First name">
            </div>
            <div class="col">
              <input name="userLastName" type="text" class="form-control" placeholder="Last name">
            </div>
          </div>
        <!----------------------------Email--------------------------------->
        <div class="md-form md-outline input-with-pre-icon">
        <div class="form-group">
          <label for="emailInfo" data-error="wrong" data-success="right"></label>
          <input name="userEmail" type="email" class="form-control" id="emailInfo" aria-describedby="emailHelp" placeholder="Enter your email">
          <small id="emailHelp" class="form-text text-muted">I'll never share your email with anyone else.</small>
        </div>
      </div>
        <!----------------------------Phone number----------------------------->
        <div class="form-group">
          <label for="exampleInputEmail1"></label>
          <input type="tel" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter your phone number">
        </div>
      </fieldset>

      <!-------------Where have you heard the website from------------->
      <div class="form-group">
        <label for="heardFrom">How did you know about this website ?</label>
        <select class="browser-default custom-select" id="heardFrom">
          <option value="browsing">Chanced upon when browsing</option>
          <option value="looking_up">Looking up on Cybersecurity</option>
          <option value="Instagram">Instagram</option>
          <option value="From_Friend">From a friend</option>
        </select>
    </div>
        <!----------------------------Text Box--------------------------------->
        <div class="form-group">
          <label name="userFeedback" for="feedbackInfo">Leave any feedback or inquiries here:</label>
          <textarea class="form-control" id="feedbackInfo" rows="3"></textarea>
        </div>
        
        <button type="submit" class="btn btn-primary">Submit</button>
        <button type="reset" class="btn btn-primary">Reset</button>
        
      </form>
    </div>
</section>





<!--------------------------------Footer----------------------------------->
<footer class="page-footer font-small bg-light text-light">
  <div class="container">
    <div class="row">
      <div class="col-md-12 py-5">
        <div class="mb-5 flex-center">
          <div class="middle">
            <a class="btn" href="#">
              <i class="fab fa-facebook-f"></i>
            </a>
            <a class="btn" href="#">
              <i class="fab fa-twitter"></i>
            </a>
            <a class="btn" href="#">
              <i class="fab fa-google"></i>
            </a>
            <a class="btn" href="#">
              <i class="fab fa-instagram"></i>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>
          

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
    
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>


    </head>

    <script>
      // API url
      const baseUrl = "http://localhost:3001";
      /
      const loggedInUserID = 1;
  
      axios.get(`${baseUrl}/spUsers/${loggedInUserID}/`)
          .then((response) => {
              const posts = response.data;
              posts.forEach((post) => {
                  const postHtml = `
                  <div class="card" style="margin-top: 2rem;">
                      <div class="card-body">
                          <p class="card-text">${post.text_body}</p>
                      </div>
                      <div class="card-footer text-muted">
                          ${post.created_at}
                      </div>
                  </div>
                  `;
                  
                  $("#posts").append(postHtml);
              });
          })
          .catch((error) => {
              console.log(error);
          });
  </script>

</body>
</html>

这是我将显示的 html 网页

这是我的 index.js 代码,它将链接前端和后端

    const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.sendFile("/public/home.html", { root: __dirname });
});

app.get("/movies/", (req, res) => {
  res.sendFile("/public/movies.html", { root: __dirname });
});


app.get("/users/:id", (req, res) => {
  res.sendFile("/public/user.html", { root: __dirname });
});

app.get("/users/", (req, res) => {
  res.sendFile("/public/users.html", { root: __dirname });
});


const PORT = 3001;
app.listen(PORT, () => {
  console.log(`Client server has started listening on port ${PORT}`);
});

这是我的 app.js,它是我使用 DOM 的后端服务的一部分

app.put("/spUsers/:userID/", isLoggedInMiddleware, (req, res, next) => {
    const userID = parseInt(req.params.userID);
    if (isNaN(userID)) {
      console.log("Userid is invalid")
      res.status(400).send();
      return;
    }

    if (userID !== req.decodedToken.user_id) { 
      console.log(userID)
      console.log(req.decodedToken.user_id)
      res.status(403).send(); 
      return; 
    }

    spUsers.edit(userID, req.body, (error) => {
      if (error) {
        console.log(error);
        if (error.code == 'ER_DUP_ENTRY') {
          res.status(422).send();
          console.log("Code reached here")
        }
        else {
          res.status(500).send();
        }
        return;
      };
      res.status(204).send();
    });
});

这是我的controller.js

var db = require('./databaseConfig.js');
var spUsers = {
findAll: function (callback) {
        var dbConn = db.getConnection();
        dbConn.connect(function (err){
            const findAllUsersQuery = "SELECT * from spmovies.users;";
            dbConn.query(findAllUsersQuery, (error, results) => {
                if (error) {
                    return callback(error, null);
                };
                return callback(null, results);
            });
        });
    }

标签: javascripthtmlmysqlserveraxios

解决方案


推荐阅读