【问题标题】:Why is my ExpressJS req.query not working?为什么我的 ExpressJS req.query 不起作用?
【发布时间】:2021-07-09 13:05:54
【问题描述】:

我有一个 NodeJS repl,它有一个输入、按钮和 h1 元素。当您按下按钮时,h1 元素内的 HTML 将替换为输入的值。这是我的代码:

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>

除了当我点击“get”时,什么都没有发生。我什至没有收到错误。为什么不? Here is the repl, if you need it.

【问题讨论】:

  • 你能记录req.query对象吗?

标签: javascript html node.js ajax express


【解决方案1】:

这是一个 cors 错误,这意味着您的服务器不期待来自同一来源的请求。默认情况下,服务器不允许这种策略以保证服务器安全,但如果您想允许,您可以将下面这段代码添加到您的 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();
});

请求完成时会出现一些解析错误,您可以解决发送 JSON 对象 intead 文本的问题。

您可以在下面找到这两个文件

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>

【讨论】:

    【解决方案2】:

    没关系,我想通了。 AJAX 设置为接收 JSON 数据,而不是字符串。它必须是这样的:

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

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2018-03-26
      • 2013-09-02
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2018-03-05
      • 2013-04-19
      相关资源
      最近更新 更多