Reputation: 365
I'm currently making an app in node.js and want to find a way to get input from html. Currently, I want a drop down menu to call a function and use the choice as input into the function. However, when I try calling a basic function (like console.log('hello world');), nothing happens. I'm using the http module to create a server and another function to return html to the user on a localhost. Here's a snippet of my code.
const http = require('http');
http.createServer(function (req, res) {
var html = buildGreeter(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
}).listen(8080);
function buildGreeter(req) {
var test = 'Test test test ';
var input = '<select onchange = "myFunc()"> <option> foo </option> <option> bar </option> </select>';
return '<!DOCTYPE html> <html><header></header><body>' + test + input + '</body></html>';
}
function myFunc(variable){
console.log(variable);
}
Should I be using another module? I know that a lot of examples online had the data sent to the server (ie via Ajax), but since I don't have a server for this project I don't know how applicable that solution is.
Thanks for the help in advance!
Upvotes: 1
Views: 78
Reputation: 40
I would use the express node module which can be installed by entering npm i express
. Here's an example of setting up a server with express with a few methods implemented as well:
const express = require('express')
const renderHtml = require('./util').renderHtml // Render HTML function
let app = express() // Get instance of express server
app.get('/', renderHtml('index.html')) // Home page
app.get('/other', renderHtml('other.html') // Other page
const port = process.env.PORT || 3000
app.listen(port, function() {
console.log(`Starting server on port ${port}`)
}
In another file (I've dubbed it util.js
) you could write functions that you wanted to execute when certain paths were called on your server. For example:
// Render any html file that I have in my './html' directory
exports.renderHtml = function (htmlFileName) {
return function (req, res) {
res.sendFile(`./html/${htmlFileName}`)
}
}
You could write a drop down list like in this example and then have the onChange action be a call to another page that you specify in your server (See first code block for example).
Upvotes: 2