简体   繁体   中英

Access SQL database from Azure Function in NodeJS

I'm trying to create an Azure Function which is triggered by a http request and then selects data from a SQL database, it then returns the data.

I've tried to set up a basic example that simply connects to a database by following the example here: https://msdn.microsoft.com/library/mt715784.aspx It isn't Azure Function specific but i thought that it should run:

var Connection = require('tedious').Connection;  
var config = {  
    userName: 'userName',  
    password: 'password',  
    server: 'databaseServer.database.windows.net',  
    options: {encrypt: true, database: 'AdventureWorks'}  
};  

module.exports = function(context, req, saasSql) {

    var connection = new Connection(config);  
    connection.on('connect', function(err) {  
        if(err) {
            context.log(err);
        } else {
            context.log("Connected");  

            context.res = {
                body: 'Connected'
            };
            context.done();
        }
    });  
};

However when this runs (triggered in the admin console). I get a log message to say that the function started and then nothing else in the logs. The Output window at the bottom gives a Status: 502 Bad Gateway and this message: Authentication is enabled for the function app. Disable authentication before running the function.

I guess that this is because I'm not calling context.done() as authentication is turned off for this function. I can't seem to work out how to get any error info etc out of the connection attempt, I've tried binding to the error event as well but nothing gets fired.

UPDATE

The error message was a bug in the Azure Functions code and was displaying the incorrect error. However, the above code still does not run (and no error is thrown). It run's fine when I create a local node server and run that way so it seems like an issue with running in the Azure Functions framework. Is there any way to connect to a SQL DB from an Azure Function?

The error message "Authentication is enabled for the function app. Disable authentication before running the function." indicates that you've enabled the Authentication / Authorization feature of your Function App. That will prevent the portal from being able to invoke your Http function because authentication is required. Note that this authentication is different than the function level authentication you configure in the Functions Portal.

So currently the only way for this to work is for you to do as the error message says - disable the Function App level auth. We have a tracking item in our repo to improve this ( issue here ).

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