【发布时间】:2018-07-13 21:54:50
【问题描述】:
我在下面的代码中有一些问题。如果有人能分解它,我将不胜感激。
我正在尝试构建一个简单的helloworldAPI。下面是代码:
var express = require('express');
var app = express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
//configuring the app for the bosy data intake for post operations
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//Configuring the app to listen to the PORT
var PORT= process.env.PORT || 3000;
//connectivity to the DB
mongoose.connect('mongodb://localhost:27017/helloworldapi');
//API Routes
var router = express.Router();
//Routes will be prefixed with /API
app.use('/api', router);
//Test route
router.get('/',function(req,res){
res.json({message: 'Welcome to our API'});
});
app.listen(PORT);
console.log('server listening on port '+PORT);
app.use(bodyParser.urlencoded({extended:true}));这里,extended: true是什么意思?
var PORT= process.env.PORT || 3000;process.env.PORT 做什么?我没有在我的环境变量中设置任何端口号。
app.use('/api', router);:这是做什么的?这是否与 API 的资源有关?
router.get('/',function(req,res){
res.json({message: 'Welcome to our API'}); : API 调用如何路由到这里的回复消息?我不清楚为什么在get方法中使用/。
最后一个问题:为什么 API 有一个单独的监听端口。我已经设置了mongoDB,它监听端口27017。我知道 API 网关有一个单独的端口来监听,但是在使用 nodeJS 时是否应该对其进行硬编码?因为我使用过 ESB 并将它们作为 API 在 WSO2 上公开。 API 网关在那里使用默认端口 9443。为什么这里应该是3000?
【问题讨论】:
-
通过谷歌搜索一下就可以轻松回答所有这些问题。阅读 Express 文档
-
嗨@Luca。感谢您的回复。我试过用谷歌搜索它们。但是我了解了代码 sn-ps 但不是整个过程。
标签: javascript node.js mongodb api