简体   繁体   中英

Node Js web services with visual studio 2017

Hi I'm used to work with c#, I'm new with node js. I'm trying to create some kind of web service using Node Js. I'm using VS 2017 community with node js version 8. I have next code:

Express App1

apps.js

app.param('phone', function (request, response, next, phone) {
// ... Perform database query and
// ... Store the user object from the database in the req object
req.phone = phone;
return next();});

index.js

'use strict';
var express = require('express');
var router = express.Router();
var Utils = require("./JavaScript1");
/* GET home page. */
router.get('/', function (req, res) {
res.render('index', { title: 'Express' });});

router.get('/byPhone/:phone', function (req, res) {   
var t = Utils.Phone(req.params.phone).then(value => { return value });    
//At this point if i try to use await or consume by using web
//http://localhost:1337/byPhone/777777 i only get a promise ...
res.send(t);
});
module.exports = router;

JavaScript1.js

function sAdd(sPhone) {
return new Promise((resolve, reject) => { // (A)
    setTimeout(() => resolve("01800" + sPhone), 5000); // (B)
});}

var utils = {
//at this point in the temp and temp2 variables only have promises
Phone:
async function (sPhone) {
    var temp = await sAdd(sPhone).then(value => { return value });
    var temp2 = await temp;
    return temp2;
}
};
module.exports = utils;

I'm trying to consume it with the next Node Js Console App:

'use strict';
async function main()
{
console.log('Hello world');
var url = "http://localhost:1337/byPhone/777777";
request(url, function (err, response, body) {
    if (err) { console.log(err); callback(true); return; }
    var tt = body;
    console.log(tt);
});
}
main();

i get the below answer:

(node:19492) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: request is not defined

I forgot to answer myself in this question, but I resolved what I wanted to do at that time this way:

I created a solution with 2 projects:

c# controllers webapp

on the c# side:

[Produces("application/json")]
    [Route("test/Mondb")]
    public class MondbController : Controller
    {
        // GET: api/Mondb
        [HttpGet]
        public string Get()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("upixTest");
            var collection = database.GetCollection<BsonDocument>("contacts");
            var document = collection.Find(new BsonDocument()).ToList();
            return document.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
        }

        // GET: api/Mondb/5
        [HttpGet("{id}", Name = "Getmdb")]
        public string Get(int id)
        {
            var filter = Builders<BsonDocument>.Filter.Eq("phone", id.ToString());
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("upixTest");
            var collection = database.GetCollection<BsonDocument>("contacts");
            var document = collection.Find(filter).FirstOrDefault();
            return (document==null) ? "nothing":document.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
        }

on the other side the node js project

functions.js

thefunctions = {
    add: function (a, b) { return a + b; }, // test function
    mongo: function () {
        var axios = require('axios');
        var tresult;
        return axios.get('http://localhost:55384/test/Mondb/');
    }
};
module.exports = thefunctions;

then in the server.js

'use strict';
var http = require('http');
var fs = require('fs');
var url = require('url');
var port = process.env.PORT || 1337;
var thefunctions = require("./thefunctions");
var dataToShow = "";
var JSON = require('JSON');

http.createServer(function (req, res) {
    var hostname = req.headers.host;
    var pathname = url.parse(req.url).pathname;
    var fullurl = 'http://' + hostname + pathname;
    var search = url.parse(req.url).search ? url.parse(req.url).search : "";

    if (pathname === "/index.html") {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('hi my friend\n');        

        var tout = thefunctions.mongo();

        tout.then(function (response) {
            res.write(JSON.stringify(response.data).toString());
            res.write('\n');
            res.end('\n\nThe End\n');
        })
            .catch(function (error) {
                console.log(error);
                res.write("error");
                res.end('\n\nThe End\n');
            });
    }
    else {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.write('error my friend\n');
        res.end('404 isnt available');
        return;
    }

    }
).listen(port);

this way you will consume c# wb services from node js app

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