小編給大家分享一下nodejs如何搭建web服務(wù)器,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

前端獲取數(shù)據(jù)時(shí)經(jīng)常會(huì)遇到跨域問(wèn)題,用 nginx 做反向代理就可以解決此問(wèn)題。但是 nginx 屬于中間件代理,不同開(kāi)發(fā)者布署的 web 服務(wù)器地址可能不一樣,這樣 nginx 的配置就不能做到通用了。
如果能有一個(gè)客戶端代理,隨著項(xiàng)目源代碼提交,這樣就可以免去不同開(kāi)發(fā)者的代理配置。webpack-dev-server 就是這樣的一個(gè)客戶端代理,但是如果項(xiàng)目沒(méi)有用到 webpack,那就沒(méi)辦法用了。那能不能仿照寫了一個(gè)簡(jiǎn)單的 web 服務(wù)器,用于非 webpack 的項(xiàng)目呢。下面是代碼,望大佬們批評(píng)指正。
const request = require('request');
const express = require('express');
const path = require('path');
const app = express();
// 代理配置
const proxyTable = {
'/api': {
target: 'http://localhost/api'
}
};
app.use(function(req, res,next) {
const url = req.url;
if (req.method == 'OPTIONS') {
console.log('options_url: ', url);
// 設(shè)置cors 跨域
// res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
// res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
// res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// 設(shè)置 cookie
// res.header("Access-Control-Allow-Credentials", true);
res.status(200).send('OK');
return;
}
// console.log('req_url: ', url);
next();
});
// 設(shè)置靜態(tài)目錄
app.use(express.static(path.join(__dirname, 'static')));
app.use('/', function(req, res) {
const url = req.url;
const proxy = Object.keys(proxyTable);
let not_found = true;
for (let index = 0; index < proxy.length; index++) {
const k = proxy[index];
const i = url.indexOf(k);
if (i >= 0) {
not_found = false;
const element = proxyTable[k];
const newUrl = element.target + url.slice(i+k.length);
req.pipe(request({url: newUrl, timeout: 60000},(err)=>{
if(err){
console.log('error_url: ', err.code,url);
res.status(500).send('');
}
})).pipe(res);
break;
}
}
if(not_found) {
console.log('not_found_url: ', url);
res.status(404).send('Not found');
} else {
console.log('proxy_url: ', url);
}
});
// 監(jiān)聽(tīng)端口
const PORT = 8080;
app.listen(PORT, () => {
console.log('HTTP Server is running on: http://localhost:%s', PORT);
});PS:static 放靜態(tài)頁(yè)面
看完了這篇文章,相信你對(duì)nodejs如何搭建web服務(wù)器有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道,感謝各位的閱讀!
分享名稱:nodejs如何搭建web服務(wù)器-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://www.chinadenli.net/article26/desijg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、網(wǎng)站策劃、網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、定制網(wǎng)站、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容