Reputation: 479
I want to retrieve a data from a database and make html file by the data. Then to connect a database from javascript I used Node.js package "pg", and to make html file I used jQuery.
But the error "jQuery requires a window with a document" has occurred.
My source code is below
server.js
var pg = require('pg');
var http = require('http');
var $ = require('jquery');
var fs = require('fs');
var conString = "postgres://uname:@localhost:5432/shop";
var server = http.createServer();
server.on('request', doRequest);
server.listen(3000, 'localhost');
function doRequest(request, response) {
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('...', function(err, result) {
response.writeHead(200, {'Content-Type': 'text/html'});
if(err) {
return console.error('error running query', err);
}
do something;
response.end();
client.end();
});
fs.readFile('./index.html', function(err, data){
var body = data.toString();
console.log($(body).find('#hoge').html());
});
});
};
I tried import "jsdom" like below but error "jsdom is not a function" has occurred.
server.js(fixed)
var pg = require('pg');
var http = require('http');
var jsdom = require('jsdom');
var fs = require('fs');
var conString = "postgres://uname:@localhost:5432/shop";
var server = http.createServer();
server.on('request', doRequest);
server.listen(3000, 'localhost');
function doRequest(request, response) {
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('...', function(err, result) {
response.writeHead(200, {'Content-Type': 'text/html'});
if(err) {
return console.error('error running query', err);
}
do something;
response.end();
client.end();
});
fs.readFile('./index.html', function(err, data){
var window = jsdom.jsdom(data.toString()).parentWindow;
var $ = require('jquery')(window);
var body = data.toString();
console.log($(body).find('#hoge').html());
});
});
};
I installed "[email protected]" and "[email protected]".
Upvotes: 1
Views: 119
Reputation: 1139
jQuery is supposed to run in a browser, not server.
Use a server side template engine, e.g. pug
Upvotes: 1