简体   繁体   中英

node.js and HTML page? How to combine?

I would like to establish a communication between a HTML-page with some JavaScript code and a simple webserver based on node.js. My first node program (demo) looks like this and i see it working by calling http:…name=someName from the web browser! Fantastic!

http = require('http');
var url = require('url');
var htmlencode = require('htmlencode');
var port = process.env.PORT || 3000;

var request = function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var parsed_url = url.parse(req.url, true)
res.write("");
res.write("<h1>Hello World</h1>");
res.write("<h2>Hello " + htmlencode.htmlEncode(parsed_url.query.name)+"</h2>");
res.write("");
res.end();
};

var server = http.createServer(request);
server.listen(port, function() {
console.log("Call server with http://localhost:" + port +"?name=");
});

Now i have my HTTP-page and i would like to start with that and then let node handle the requests. I assume, i have to load it from node, but how? Or do i simply load it by calling the page and then switch to node, but how again? I guess communication from my page is done by AJAX?

Thanks for any help and i would appreciate some sample code! Peter

Now i have my HTTP-page and i would like to start with that and then let node handle the requests. I assume, i have to load it from node, but how?

You've written an anonymous function and assigned it to a variable called request . You've set up your program so every time your server gets a request, that function creates a response to it.

If you want to respond to requests for your HTML page with your HTML page, then you need to change that function so it responds with the HTML page you want.

Presumably, that will be writing a condition to check what URL was requested (the details are in the object assigned to req ) and then either do what you are doing now, or read the HTML file and send its contents.

Or do i simply load it by calling the page and then switch to node, but how again?

Then you run two HTTP servers and will have to use absolute URLs to reference one from the other.

I guess communication from my page is done by AJAX?

There's no need to involve client-side JavaScript at all. A regular form submission should do fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM