【发布时间】: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