[英]Node Js web services with visual studio 2017
嗨,我曾經使用過C#,而Node js是我的新手。 我正在嘗試使用Node Js創建某種Web服務。 我正在將VS 2017社區與Node js版本8一起使用。我有下一個代碼:
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;
我正嘗試在下一個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();
我得到以下答案:
(節點:19492)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):ReferenceError:未定義請求
我忘記在這個問題上回答自己,但是我以這種方式解決了當時想做的事情:
我創建了一個包含2個項目的解決方案:
C#控制器WebApp
在C#端:
[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 });
}
在另一方面,節點js項目
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;
然后在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);
這樣,您將使用Node js應用程序中的c#wb服務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.