簡體   English   中英

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

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

我有一個 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);

索引.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”時,什么都沒有發生。 我什至沒有收到錯誤。 為什么不? 這是repl,如果你需要的話。

這是一個 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 object 文本的問題。

您可以在下面找到這兩個文件

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);

索引.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>

沒關系,我想通了。 AJAX 設置為接收 JSON 數據,而不是字符串。 它需要像:

$.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