亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

node.js根據(jù)不同請求路徑返回不同數(shù)據(jù)詳解流程

 更新時間:2021年10月26日 09:40:50   作者:yyy言者  
本篇文章介紹了我在開發(fā)過程中發(fā)現(xiàn)的一個小問題,就是node.js如何能夠根據(jù)不同的請求路徑來返回得到不同數(shù)據(jù),通讀本篇對大家的學習或工作具有一定的價值,需要的朋友可以參考下

1.學習根據(jù)不同的請求路徑返回:不同數(shù)據(jù)

var url=req.url //獲取req.url值(req:是request簡寫)
req.url: 獲取的是端口號之后的路徑
實現(xiàn)不同路徑返回不同數(shù)據(jù)

我的端口號:3000,網(wǎng)址:http://127.0.0.1:3000

if(url==='/'){

res.end(‘index page') //如果輸入的網(wǎng)址為:http://127.0.0.1:3000/
//響應括號里數(shù)據(jù),把數(shù)據(jù)傳到服務器中顯示
}

if(url==='/login')
{

res.end(‘login page') //如果輸入的網(wǎng)址為:http://127.0.0.1:3000/login
//響應括號里數(shù)據(jù),把數(shù)據(jù)傳到服務器中顯示
}

在這里插入圖片描述

var http = require("http"); // http 模塊
http.createServer(function(req, res) {
//res.write('hello')
//res.write('world!')
 // res.end('index page');

var url=req.url           //獲取req.url值

if(url==='/'){

res.end('index page') //內(nèi)容結(jié)束

}else if(url==='/login')
{

res.end('login page')


}else{

  res.end('404')
}

console.log(req.url);

}).listen(3000); // 監(jiān)聽端口3000
 
console.log("HTTP server is listening at port 3000.網(wǎng)址為http://127.0.0.1:3000");

結(jié)果:

在這里插入圖片描述

在這里插入圖片描述

2.發(fā)送的數(shù)據(jù):數(shù)據(jù)類型,和什么編碼:Content-Type

res.setHeader(‘Content-Type',‘text/plain; charset=utf-8')
res.setHeader(‘Content-Type',‘text/html; charset=utf-8')

text/plain :文本 plain:普通的
如果內(nèi)容是html標簽,需要改: text/html
res.end(“helloworld”); 用text/plain

res.end('<p>我是誰<a>點擊</a></p>')//用 text/html,才能被瀏覽器識別到

charset=utf-8:內(nèi)容以:這個utf-8編碼

在這里插入圖片描述

3.關于讀入文件的:相對路徑和絕對路徑:

這個相對路徑實際上是相對于執(zhí)行node命令所處的路徑:

var fs=require(“fs”) //fs有很多API函數(shù),獲取fs對象
fs.readFile()//讀人文件
我執(zhí)行node命令在:d:\node1.js
文件07.html在:d:node1.js目錄下 ;
所以:fs.readFile('./07.html',funtion(){ })
就能讀取文件;把內(nèi)容傳給data

res.end(data)
就把html內(nèi)容寫在了:res.red()中
打開網(wǎng)頁就能看見s.end中

在這里插入圖片描述

在這里插入圖片描述

var http = require("http"); // http 模塊
var fs=require("fs")
   //var url=req.url;
http.createServer(function(req, res) {


//res.write('hello')
//res.write('world!')
 // res.end('index page');
 fs.readFile('./07.html',function(err,data) {
    
if(err){

res.setHeader('Content-Type','text/plain; charset=utf-8')

     res.end('wss')

}
else{

res.setHeader('Content-Type','text/html; charset=utf-8')
res.end(data)

}

 })


}).listen(3000);
console.log("服務")

結(jié)果:

在這里插入圖片描述

4.讀圖片

fs.readFile('./07.jpg',function(err,data)
res.setHeader(‘Content-Type',‘image/jpeg; charset=utf-8')
res.end(data)
//主要代碼

到此這篇關于node.js根據(jù)不同請求路徑返回不同數(shù)據(jù)詳解流程的文章就介紹到這了,更多相關node.js 請求路徑與數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論