Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

javascript - Is there a way to tell when I receive an ajax request with node/express?

I'm running a node/express server that sends the ajax-start.html file. The ajax-start.html files has a script in it that makes ajax requests to the server. All that works fine. However when the server receives an ajax request I want to be able to modify the text file before sending it. (I'm very new to this, and trying to modify an example from MDN to fit my needs.)

The HTML (ajax-start.html):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Ajax starting point</title>

    <style>
      html,
      pre {
        font-family: sans-serif;
      }

      body {
        width: 500px;
        margin: 0 auto;
        background-color: #ccc;
      }

      pre {
        line-height: 1.5;
        letter-spacing: 0.05rem;
        padding: 1rem;
        background-color: white;
      }

      label {
        width: 200px;
        margin-right: 33px;
      }

      select {
        width: 350px;
        padding: 5px;
      }
    </style>
    <!--[if lt IE 9]>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
    <![endif]-->
  </head>

  <body>
    <h1>Ajax starting point</h1>

    <form>
      <label for="verse-choose">Choose a verse</label>
      <select id="verse-choose" name="verse-choose">
        <option>Verse 1</option>
        <option>Verse 2</option>
        <option>Verse 3</option>
        <option>Verse 4</option>
      </select>
    </form>

    <h2>The Conqueror Worm, <em>Edgar Allen Poe, 1843</em></h2>

    <pre></pre>

    <script>
      const verseChoose = document.querySelector("select");
      const poemDisplay = document.querySelector("pre");

      verseChoose.onchange = function () {
        const verse = verseChoose.value;
        updateDisplay(verse);
      };

      function updateDisplay(verse) {
        verse = verse.replace(" ", "");
        verse = verse.toLowerCase();
        let fname = verse + ".txt";
        let url = `textFiles/${fname}`;

        let request = new XMLHttpRequest();
        request.open("GET", url);
        request.responseType = "text";

        request.onload = function () {
          poemDisplay.textContent = request.response;
        };
        request.send();
      }
    </script>
  </body>
</html>

The node/express(app.js)

const express = require("express");
const fs = require("fs");
const app = express();
app.use(express.static(`assets`));

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/ajax-start.html");
});

app.listen(5000, () => {
  console.log(`listening`);
});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no way to detect Ajax requests per se, but HTTP has a number of options for providing different versions of content.

If you want to provide the same data in a different format (it is quite common to e.g. HTML for a direct request and JSON for an Ajax request) then you can make use of the Accept header (with your server-side code defaulting to HTML unless the Accept header (available via req.headers) expresses a preference for JSON).

If you want to provide subtly different content then you can use a query string (req.query) on the URL.

Significantly different content is generally better off with a different endpoint entirely.

You can also make use of the X-Requested-With, which is non-standard, but you can add it (like an Accept header) with setRequestHeader as that is a common pattern for expressing "This is Ajax". It does avoid standard approaches though, so I don't recommend it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...