![](/img/trans.png)
[英]Relationship of node.js / Express / Connect / Socket.io
[英]Node.js and Express relationship
我試圖了解Node.js和Express之間的連接。
我用於創建Node.js服務器的代碼:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, function(req,res){
res.writeHead(200);
res.end(`Hello world!!!!!!!!!!! \n`);
});
server.listen(3000, function(){
console.log('Server listening on port 3000 \n');
});
我運行curl操作curl -k localhost:3000
,它給我一個“ Hello World”輸出
我用於創建Express Server的代碼:
// call the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES FOR OUR API
var router = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(port);
console.log('Magic happens on port ' + port);
我們是否可以將兩者混合使用?
更具體地說,我想使用Node.js方式創建服務器,但是要使用Express方式創建路由。 我可以這樣做還是應該只采用一種方法? Node.js和Express之間的連接是什么? 我知道Express只是Node.js的框架,但是如果有的話,偏差到底發生在哪里?
我可以在需要時將兩者混合並結合嗎?
謝謝
您肯定可以通過這種方式在大多數項目中創建帶有Express和Follow的安全HTTPS服務器
const https = require('https'); const express = require('express'); const app = express(); const options = { key: fs.readFileSync('./https1/key.pem'), cert: fs.readFileSync('./https1/cert.pem') }; const server = https.createServer(options, app); app.get('/', (req, res) => { res.send('hello world') } server.listen(config.port, () => { console.log(`Express server listening on port ${port} in ${app.get('env')} mode`); });
現在添加您的路線和所有路線。
是的,您可以結合使用nodejs
和express
,但是不鼓勵您結合使用它們,除非您有特定的用途,例如使用AWS lambda
或執行僅由純節點執行的特定OS任務。
如您所知, express
只是一個框架。 您可以使用express
編寫代碼。
例如,要使瀏覽器顯示“ Hello world”,
// nodejs version
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// express version
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (req, res) => {
res.send('Hello World!\n');
})
更容易,更直觀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.