У меня есть Node-сервер, который обслуживает различные HTML страницы. На одной из страниц есть форма. При щелчке по форме конечная точка на сервере узла. js файл использует данные формы. Эта же страница HTML содержит элемент
, текстовое содержимое которого я хотел бы изменить при отправке формы. Я видел различные онлайн-учебники, демонстрирующие, как использовать document.getElementById('predictionText').innerHTML = prediction;
для динамической установки значения текста с использованием встроенного javascript. Как мне добиться этого, используя Node и внешний js?
Ниже мой код:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body class="bodyContent">
<p>This is the predictor page -- it will hold a form for the user to input relevant data to.</p>
<section class="active" id="navigationBarSection">
<ul>
<li><a href="index">Home</a></li>
<li><a href="predictor">Predictor</a></li>
<li><a href="how_it_works">How it Works</a></li>
<li><a href="about_us">About Us</a></li>
</ul>
</section>
<section id="predictorUserInputSection">
<form action="/post_data_to_predictor_algorithm" method="POST" id="attributeInputForm">
<input class="textInput" required name="averageAreaIncome" placeholder="Average Area Income" />
<input class="textInput" required name="averageAreaNumberOfRooms" placeholder="Average Area Number of Rooms" />
<input class="textInput" required name="averageAreaHouseAge" placeholder="Average Area House Age" />
<input class="textInput" required name="averageAreaNumberOfBedrooms" placeholder="Average Area Number of Bedrooms"/>
<input class="textInput" required name="areaPopulation" placeholder="Area Population"/>
<button id="submitButton">Submit</button>
</form>
</section>
<section id="predictionResultsSection">
<p id="predictionText"><font size="6">here </p>
</section>
<script src="server.js"></script>
</body>
</html>
Узловой сервер, который должен обновить текст:
//jshint esversion:8
//adding all required dependencies/packages
const express = require('express');
const path = require('path');
const fs = require("fs");
const bodyParser = require('body-parser'); //for parsing post requests
const request = require('request') //for making HTTP requests
//specifies that this app will be using express.
const app = express();
//middleware for processing POST requests a bit easier.
app.use(bodyParser.urlencoded({extended: false}));
//static AWS EC2 instance server port. Edit with caution.
const serverPort = 5001;
const FLASK_SERVER_LOCAL_ENDPOINT = "http://localhost:5000/predictPrice";
//Allow the use of static files in project directory
app.use('/js', express.static(__dirname + '/js'));
app.use('/html', express.static(__dirname + '/html'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use('/resources', express.static(__dirname + '/resources'));
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
//Handle all root requests.
app.get("/", function(req, res) {
res.sendFile(path.resolve("index.html"));
});
app.get("/index", function(req, res) {
res.sendFile(path.resolve("index.html"));
});
app.get("/predictor", function(req, res) {
res.sendFile(path.resolve("html/predictor.html"));
});
app.get("/how_it_works", function(req, res) {
res.sendFile(path.resolve("html/how_it_works.html"));
});
app.get("/about_us", function(req, res) {
res.sendFile(path.resolve("html/about_us.html"))
});
//HERE IS THE PROBLEM
app.post("/post_data_to_predictor_algorithm", (req, res) => {
//update prediction label in the UI:
console.log("Updating label!");
document.getElementById('predictionText').innerHTML = "received user response!";
});
При запуске сервера я получаю следующую ошибку при отправке формы:
ReferenceError: document is not defined
at app.post (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/server.js:90:3)
at Layer.handle [as handle_request] (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/layer.js:95:5)
at /Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/index.js:335:12)
at next (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/express/lib/router/index.js:275:10)
at /Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Users/vismarkjuarez/Documents/Github/RealEstatePriceEstimator/node_modules/raw-body/index.js:224:16)