1

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]".

1 Answer 1

1

jQuery is supposed to run in a browser, not server.

Use a server side template engine, e.g. pug

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.