如何利用nodejs搭建web服務(wù)器?

2021-02-05    分類: 網(wǎng)站建設(shè)

Node.js 是一個(gè)基于 Chrome V8 引擎的 JavaScript 運(yùn)行環(huán)境。 Node.js 使用了一個(gè)事件驅(qū)動(dòng)、非阻塞式 I/O 的模型,使其輕量又高效。Node.js 的包管理器 npm,是全球大的開源庫生態(tài)系統(tǒng)。(nodejs官網(wǎng)上的介紹),正如官網(wǎng)上介紹的那樣,nodejs確實(shí)很牛!怎么個(gè)牛法?看看下面的代碼就知道了。

//引入http模塊

var http = require("http");

//設(shè)置主機(jī)

var hostName = '127.0.0.1';

//設(shè)置端口

var port = 8080;

//創(chuàng)建服務(wù)

var server = http.createServer(function(req,res){

res.setHeader('Content-Type','text/plain');

res.end("hello nodejs");

});

server.listen(port,hostName,function(){

console.log(`服務(wù)器運(yùn)行在http://${hostName}:${port}`);

});

短短幾行代碼就把一個(gè)簡單的web服務(wù)器搭建完成了,為了驗(yàn)證效果,我們在瀏覽器請求,結(jié)果如下


運(yùn)行成功!

到此為止,一個(gè)web服務(wù)器就建立成功了! 沒錯(cuò)就是這么簡單,然后我們就可以寫個(gè)html界面愉快的玩耍了,哈哈哈!果斷的寫了一個(gè)html頁面來請求一下我們的web服務(wù)器。


 
 Document
 
 
獲取數(shù)據(jù)
function getText(){ $(".text").load("http:127.0.0.1:8080"); }

代碼簡單,點(diǎn)擊div獲取數(shù)據(jù)并將服務(wù)器返回的數(shù)據(jù)展示。好了,我們運(yùn)行一下demo.html文件,我擦來!居然出現(xiàn)了……


很明顯,通過jquery請求不到數(shù)據(jù),這是因?yàn)榭缬蛘埱蟮脑?。我們的web服務(wù)器并不支持跨域請求,所以報(bào)錯(cuò)了。解決方式:在服務(wù)器的響應(yīng)頭文件里加上如下代碼:

res.setHeader('Content-Type','text/plain');
 res.setHeader('Access-Control-Allow-Origin',"*")
 res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
 res.end("hello nodejs");

再次重啟服務(wù)器,運(yùn)行demo.html,顯示結(jié)果很是令人欣喜!


通常請求服務(wù)器都會(huì)拼接參數(shù)的,最常用的就是get請求,post請求。很明顯,我們現(xiàn)在的代碼還不能支持。express框架很好的封裝了nodejs的http模塊,使我們用起來非常的簡單。

引入express :$ cnpm install express –save

var express = require("express");
var app = express();
var hostName = '127.0.0.1';
var port = 8080;
app.all('*', function(req, res, next) { 
 res.header("Access-Control-Allow-Origin", "*"); 
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
 res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); 
 res.header("X-Powered-By",' 3.2.1') 
 res.header("Content-Type", "application/json;charset=utf-8"); 
 next(); 
});
app.get("/get",function(req,res){
 console.log("請求url:",req.path)
 console.log("請求參數(shù):",req.query)
 res.send("這是get請求");
})
app.listen(port,hostName,function(){
 console.log(`服務(wù)器運(yùn)行在http://${hostName}:${port}`);
});

使用方式變化不大,通過express()方法開啟服務(wù),然后在通過get方法來設(shè)置匹配參數(shù)的路由,通過在回調(diào)函數(shù)的req中可以獲取請求參數(shù)和地址。post請求也是類似,不過有不同的是,post請求在獲取參數(shù)的時(shí)候要引入body-parser 中間件,用于處理 JSON, Raw, Text 和 URL 編碼的數(shù)據(jù)。

var express = require("express");
var bodyParser = require("body-parser"); 
var app = express(); 
app.use(bodyParser.urlencoded({ extended: false })); 
var hostName = '127.0.0.1';
var port = 8080;
app.all('*', function(req, res, next) { 
 res.header("Access-Control-Allow-Origin", "*"); 
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
 res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); 
 res.header("X-Powered-By",' 3.2.1') 
 res.header("Content-Type", "application/json;charset=utf-8"); 
 next(); 
});
app.get("/get",function(req,res){
 console.log("請求url:",req.path)
 console.log("請求參數(shù):",req.query)
 res.send("這是get請求");
})
app.post("/post",function(req,res){
 console.log("請求參數(shù):",req.body);
 var result = {code:200,msg:"post請求成功"};
 res.send(result);
});
app.listen(port,hostName,function(){
 console.log(`服務(wù)器運(yùn)行在http://${hostName}:${port}`);
});

運(yùn)行結(jié)果:


完整的get以及post請求就是以上了。下一篇文章會(huì)結(jié)果fs文件模塊介紹http是如何返回文件的,敬請期待?。?/p>

名稱欄目:如何利用nodejs搭建web服務(wù)器?
本文鏈接:http://www.muchs.cn/news4/99354.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、電子商務(wù)網(wǎng)站策劃、響應(yīng)式網(wǎng)站、ChatGPT、域名注冊

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)