简体   繁体   English

为什么我的 ExpressJS req.query 不起作用?

[英]Why is my ExpressJS req.query not working?

I have a NodeJS repl, which has an input, button, and h1 element.我有一个 NodeJS repl,它有一个输入、按钮和 h1 元素。 When you press the button, the HTML inside of the h1 element will replace with the value of the input.当您按下按钮时,h1 元素内的 HTML 将替换为输入的值。 Here is my code:这是我的代码:

index.js: 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:索引.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.除了当我点击“get”时,什么都没有发生。 I don't even get an error.我什至没有收到错误。 Why not?为什么不? Here is the repl, if you need it.这是repl,如果你需要的话。

This is a cors error, which means your server is not expecting requests from the same origin.这是一个 cors 错误,这意味着您的服务器不期望来自同一来源的请求。 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.默认情况下,服务器不允许这种策略以保证服务器安全,但如果你想允许,你可以将下面的这段代码添加到你的 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.请求完成时会出现一些解析错误,您可以解决发送 JSON object 文本的问题。

Below you can find both files您可以在下面找到这两个文件

index.js 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索引.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. AJAX 设置为接收 JSON 数据,而不是字符串。 It needed to be like:它需要像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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