Initialize a Node.js server and connect to MS SQL

Asked

Viewed 206 times

-2

I’m starting to use Node.js and developing web applications, I believe this is a very basic doubt, but I found nowhere a solution to my problem.

I need to connect my . js with MS SQL, found the following code and implemented it to my script.js file:

var sql = require("mssql");
var config = {
    user: 'xxxxx',
    password: 'xxxxx123',
    server: 'xxxxx',
    database: 'xxxxxx'
};
// connect to your database
sql.connect(config, function (err) {

    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();

    // query to the database and get the records
    request.query('select * from teste', function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset);

    });
});

But he received the error:

Uncaught Referenceerror: require is not defined

I found that I needed to run a Node server, since the require function is not recognized by the browser.

I ran the following code in a separate file called server.js to get the server running and access my project from the localhost:

var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');

var mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css"};

http.createServer((request, response)=>{
    var pathname = url.parse(request.url).pathname;
    var filename = String;
    if(pathname === "/"){
        filename = "index.html";
    }
    else
        filename = path.join(process.cwd(), pathname);

    try{
        fs.accessSync(filename, fs.F_OK);
        var fileStream = fs.createReadStream(filename);
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {'Content-Type':mimeType});
        fileStream.pipe(response);
    }
    catch(e) {
            console.log('File not exists: ' + filename);
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
    }
    return;
    }
).listen(8080);

And now, even accessing port 8080 by browser I keep getting the same error... I don’t know where else to go, anyone could help me or give me a direction to go?

1 answer

1

Good afternoon Luiz, I don’t know your need but if in the future you need use routes, try using express, is super easy and has a lot of content on the net.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.