简体   繁体   中英

Why is my ExpressJS req.query not working?

I have a NodeJS repl, which has an input, button, and h1 element. When you press the button, the HTML inside of the h1 element will replace with the value of the input. Here is my code:

index.js:

const Database = require("@replit/database");
const db = new Database();
const http = require("http");
const fs = require("fs");
const express = require("express");
const app = express();

app.use(express.static(__dirname + "/public"));

app.get("/ajaxcall", async function(req, res) {
// db.set("this works?", "it does").then(() => {console.log(db.get("this works?"))});
res.send(req.query.keyUse);
})

app.get('/:id', function(request, response){
   fs.readFile(`${request.url == '/ajaxcall' ? '/ajaxcall' : String(request.url).substring(1)}`, null, function(error, data) {
        if (error) {
            response.writeHead(404);
            response.write('File not found!');
        } else {
          response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data);
        }
        response.end();
    });
});

app.listen(8000);
// http.createServer(onRequest).listen(8000);

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <h1 id="replace">meep</h1>
  <input id="getkey">
  <button id="button" onclick="get()">get</button>

  <script>
    function get() {
      $.ajax({
        type: 'GET',
        url: `https://databasetest.aquarial.repl.co/ajaxcall?keyUse=${document.querySelector('#getkey').value}`,
        dataType: 'json',
      })
      .done(function (data) {
        console.log('Response:', JSON.stringify(data, "", 2));
        $('#replace').html(JSON.stringify(data, "", 2));
      })
      .fail(function (jqXJR, textStatus, err) {
        console.log('Error:', textStatus);
      })
    }
  </script>
</body>
</html>

Except when I hit "get", nothing happens. I don't even get an error. Why not? Here is the repl, if you need it.

This is a cors error, which means your server is not expecting requests from the same origin. By default servers does not allow this kind of policy in order to keep the server secure, but if you want to allow this you can and add this piece of code below to your index.js.

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader("Access-Control-Request-Headers", "x-requested-with"); //according jquery docs it only works with this header.
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET"
  );
  next();
});

There are some parse errors in when the request is fullfiled and you can solve the problem sending a JSON object intead text.

Below you can find both files

index.js

const Database = require("@replit/database");
const db = new Database();
const http = require("http");
const fs = require("fs");
const express = require("express");
const app = express();

app.use(express.static(__dirname + "/public"));

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader("Access-Control-Request-Headers", "x-requested-with");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET"
  );
  next();
});

app.get("/ajaxcall", async function(req, res) {
  // db.set("this works?", "it does").then(() => {console.log(db.get("this works?"))});
  res.send({ msg:req.query.keyUse});
})

app.get('/:id', function(request, response) {
  fs.readFile(`${request.url == '/ajaxcall' ? '/ajaxcall' : String(request.url).substring(1)}`, null, function(error, data) {
    if (error) {
      response.writeHead(404);
      response.write('File not found!');
    } else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.write(data);
    }
    response.end();
  });
});

app.listen(8000);
// http.createServer(onRequest).listen(8000);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <h1 id="replace">meep</h1>
  <input id="getkey">
  <button id="button" onclick="get()">get</button>

  <script>
    function get() {
      // window.log(document.querySelector('#getkey').value)
      $.ajax({
        type: 'GET',
        url: `https://databasetest.aquarial.repl.co/ajaxcall?keyUse=${document.querySelector('#getkey').value}`,
        dataType: 'json',
      })
      .done(function (data) {
        console.log('Response:', JSON.stringify(data, "", 2));
        $('#replace').html(data.msg);
      })
      .fail(function (jqXJR, textStatus, err) {
        console.log('Error:', textStatus);
      })
    }
  </script>
</body>
</html>

Nevermind, I figured it out. The AJAX was set to receiving JSON data, not a string. It needed to be like:

$.ajax({
        type: 'GET',
        url: `https://databasetest.aquarial.repl.co/ajaxcall?keyUse=${document.querySelector('#getkey').value}`,
        dataType: 'text',
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM