SQL Server node mssql - req.app.locals.pool.input is not a function

mzillmmw  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(109)

I'm trying to follow the documentation for node mssql on creating pools.

I get this error...

TypeError: req.app.locals.pool.input is not a function

With this code...

server.js

const express = require("express");
const app = express();

const sql = require("mssql");
const { db } = require("./config.js");
const poolConnection = new sql.ConnectionPool(db);

const PORT = process.env.PORT || 9010;

//connect the pool and start the web server when done
poolConnection
    .connect()
    .then((pool) => {
        app.locals.pool = pool; //    <------- HERE

        const server = require("http").createServer(app);

        server.listen(PORT, () => {
            console.log(`listening on port: ${PORT}`);
        });
    })
    .catch((err) => {
        console.error("Error creating connection pool", err);
    });

route.js

router.get("/api/users/:userId", async (req, res, next) => {
    try {
        let userId = req.params.userId;

        req.app.locals.pool.input("userId", sql.Int, userId); //    <------- HERE

        let query = `
            select *
            from bi_user u
            where u.id = @userId    
            ;
        `;

        let result = await req.app.locals.pool.query(query);

        let final = result.recordset[0];

        res.send(final);
    } catch (err) {
        next(err);
    }
});

What am I doing wrong?

vfh0ocws

vfh0ocws1#

Solved it like this...

router.get("/api/users/:userId", async (req, res, next) => {
    try {
        let userId = req.params.userId;

        let request = req.app.locals.pool; //    <------- WITH THIS

        request.input("userId", sql.Int, userId); 

        let query = `
            select *
            from bi_user u
            where u.id = @userId    
            ;
        `;

        let result = await request.query(query);

        let final = result.recordset[0];

        res.send(final);
    } catch (err) {
        next(err);
    }
});

相关问题