简体   繁体   中英

How to get JSON data from node.js to HTML

I am trying to create a web app with some drop down menus that contain data from a sql server database. After some searching I figured out how to use node.js to output the table data into the command prompt.

 var sql = require('mssql/msnodesqlv8'); var config = { connectionString: 'Driver=SQL Server;Server=NAME\\\\SQLEXPRESS;Database=master;Trusted_Connection=true;' }; sql.connect(config, err => { new sql.Request().query('SELECT * FROM TABLE', (err, result) => { console.log("Works"); if(err) { // SQL error, but connection OK. console.log(" Error: "+ err); } else { // All good. console.dir(result); }; }); }); sql.on('error', err => { // Connection bad. console.log("Bad"); console.log(" Error: "+ err); }); 

Now the problem is I don't know how to get that result into JSON data that can be used in my web app. Any help would be appreciated as I am quite new to node.js. Thanks!

EDIT: Thanks for the help so far! I added the following code for when there is no error:

 var express = require('express') var app = express() JSON.stringify(result); console.log(JSON.stringify(result)); app.get('/', function (req, res) { res.send(result) }) 

I also have all of the code for the http server but I don't think it's necessary to show it all. Is this all that is needed on the server side?

First of all, to send data from the server to the client you'll have to run an HTTP server as part of your Node backend. Then, once the web app loads, it should make a request to your server, which as a response will return the data from the database. For more information on how to do this check out Express (for the server side) and Fetch API (for the client side).

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