在NodeJs中创建路由[关闭]

问题描述 投票:-2回答:1

我在数据库中有此表:

      CREATE TABLE dbo.Products  
      (ProductID int PRIMARY KEY NOT NULL,  
      ProductName varchar(50) NOT NULL,  
      Price money NULL)  
      GO

并且我用1000行数据填充了该表。如何在NodeJs项目中创建“产品路由器”?

node.js
1个回答
-1
投票

您可以使用express公开您产品的服务,该服务将与您的数据库通信,您可以在数据库上对products表执行CRUD操作。例如

var express = require('express')
var app = express();
var mysql = require('mysql');


var con = mysql.createConnection({
  host: "yourHost",
  user: "yourusername",
  password: "yourpassword",
  port:"yourPort"

});


app.get('/products', function (req, res) {
   con.connect(function(err) {
     if (err) throw err;
     con.query("SELECT * from records", function (err, result) {
       if (err) throw err;
       con.close();
       res.send(JSON.stringify(result))
    });
  });
})

app.listen(3000);

将此代码放入节点项目的index.js文件或main.js文件中。之后,打开您的终端并使用CURL测试您的服务。curl -X POST“ http://localhost:3000/products”。或者,您只需在浏览器中键入http://localhost:3000/products,它就会为您提供所有产品记录。

© www.soinside.com 2019 - 2024. All rights reserved.