我在本地網路上為服務器運行了兩個埠:27017 是 MongoDB 的埠,3000 是我的 nodejs 應用程式的埠。然后我在偵聽埠 3000 的同時使用 mongoose connect 連接兩者。
var db = mongoose.connect('mongodb://localhost/test')
app.listen(3000, () => {
console.log('listening on port 3000')
})
以前,我試圖通過 Web 瀏覽器使用 http://(server ip):27017 連接到服務器,但我在 NodeJS 應用程式中撰寫的 GET 永遠不會被呼叫。
app.get('/', (req, res) => {
res.send('hello world')
})
我將埠切換到 3000,http://(server ip):3000,最后我得到了來自 GET 的回應。
那么客戶端應該如何連接到他們的服務器呢?通過他們的 nodejs 應用程式而不是資料庫?使用 TLS 和 HTTP 時,客戶端是否也應該連接到 nodejs 應用程式?
uj5u.com熱心網友回復:
瀏覽器客戶端應該連接到您的 Web 服務器,而不是連接到資料庫,因此在上面的示例中,它會在埠 3000 上。
那么客戶端應該如何連接到他們的服務器呢?通過他們的 nodejs 應用程式而不是資料庫?
是的。資料庫供您的服務器使用,而不是供客戶端直接使用。任何客戶端與資料庫的互動都是通過您的服務器間接發生的。
使用 TLS 和 HTTP 時,客戶端是否也應該連接到 nodejs 應用程式?
如果服務器在本地運行,僅使用 localhost 訪問它,則可能不需要 https。
現在通常建議在 https 上運行公共服務器。這意味著您將從Let's Encrypt 之類的證書頒發機構獲得證書,并https.createServer()在像 Let's Encrypt 網站上的這個示例的一般方案中與 https 憑據選項一起使用:
// Dependencies
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
// Certificate
const privateKey = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
app.use((req, res) => {
res.send('Hello there !');
});
// Starting https server
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(443, () => {
console.log('HTTPS Server running on port 443');
});
請注意,您通常會在埠 443 上運行 https 服務器。然后,您將使用https協議而不是http. 如果您使用 443(https 的默認埠號),則不需要在瀏覽器 URL 中指定埠,但如果不使用埠 443,則需要指定埠。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345936.html
