我剛剛開始玩nodeJs。目前,我有這樣的項目:Nodejs基礎知識:我可以如何使用require(模塊)?
結構: - app.js - response.js
app.js代碼:
var callback = require('./response.js');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.post('/test', callback);
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function() {
console.log('Slack bot listening on port ' + port);
});
我response.js是:
module.exports = function (req, res, next) {
return res.status(200).json({
attachments: [{ "test": "test" }})]
});
}
正如您在這裏所看到的,我使用express服務器來偵聽發送到/測試端點的請求,並用一些測試json響應這些請求。
問題:我想使用mongo - 從數據庫中獲取相同的數據,並在觸發/ test端點時返回響應。 MongoDB的教程指導我安裝MongoDB的NPM模塊,然後包括MongoDB的模塊和做其他例如像這樣:
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
- 我可以要求MongoDB的(要求(「mongodb的」))在response.js ?如果是,它應該在函數內還是在module.exports之外?
- 如果我在app.js中需要('mongodb')有沒有辦法在response.js中使用它?
是的,你可以在response.js中要求mongodb,它應該在導出之外。如果你需要app.js中的mongodb,你將無法使用它在response.js – SKY
謝謝天空,如果你將這添加爲適當的答案我會選擇是正確的。 – Tautvydas
我已經添加它作爲回答 – SKY