您好,登錄后才能下訂單哦!
NODE代理訪問(wèn)
1. 場(chǎng)景
2. 技術(shù)框架
3. 上代碼
3.1 創(chuàng)建應(yīng)用 app.js
const Koa = require('koa') const bodyParser = require('koa-bodyparser') // 路由 const router = require('./router') const app = new Koa() app.use( bodyParser({ // 返回的對(duì)象是一個(gè)鍵值對(duì),當(dāng)extended為false的時(shí)候,鍵值對(duì)中的值就為'String'或'Array'形式,為true的時(shí)候,則可為任何數(shù)據(jù)類型。 extended: true }) )
3.2 允許跨域 app.js
app.use(async (ctx, next) => { ctx.set('Access-Control-Allow-Origin', '*') ctx.set('Access-Control-Allow-Headers', 'content-type') ctx.set( 'Access-Control-Allow-Methods', 'OPTIONS,GET,HEAD,PUT,POST,DELETE,PATCH' ) await next() })
3.2 使用路由
// app.js app.use(router.routes()) // router.js const Router = require('koa-router') let koaRequest = require('./httpRequest') const router = new Router() router.get('/*', async (ctx, next) => { const url = setQuestUrl(ctx.url) try { let res = await koaRequest(url, 'GET', ctx) ctx.body = res } catch (err) { ctx.body = err } }) router.post('/*', async (ctx, next) => { const url = setQuestUrl(ctx.url) try { let res = await koaRequest(url, 'POST', ctx) ctx.body = res } catch (err) { ctx.body = err } }) function setQuestUrl(url) { if (/^\/t/.test(url)) { return 'host1'+ url.replace(/^\/t/, '') } if (/^\/xt/.test(url)) { return 'host2' + url.replace(/^\/xt/, '') } } module.exports = router
const Koa = require('koa2'); const app = new Koa(); // logger app.use(async (ctx, next) => { console.log('第一層洋蔥 - 開(kāi)始') await next(); const rt = ctx.response.get('X-Response-Time'); console.log(`${ctx.method} ${ctx.url} - ${rt}`); console.log('第一層洋蔥 - 結(jié)束') }); // x-response-time app.use(async (ctx, next) => { console.log('第二層洋蔥 - 開(kāi)始') const start = Date.now(); await next(); const ms = Date.now() - start; ctx.set('X-Response-Time', `${ms}ms`); console.log('第二層洋蔥 - 結(jié)束') }); // response app.use(async ctx => { console.log('第三層洋蔥 - 開(kāi)始') ctx.body = 'Hello World'; console.log('第三層洋蔥 - 結(jié)束') }); app.listen(8000); // 輸出 第一層洋蔥 - 開(kāi)始 第二層洋蔥 - 開(kāi)始 第三層洋蔥 - 開(kāi)始 第三層洋蔥 - 結(jié)束 第二層洋蔥 - 結(jié)束 第一層洋蔥 - 結(jié)束
setQuestUrl 此方法主要是將前端訪問(wèn)的路徑,根據(jù)第一級(jí)轉(zhuǎn)發(fā)到不同的host上
例如: /t -> host1
3.3 轉(zhuǎn)發(fā)請(qǐng)求 httpRequest.js
本例主要為了代理訪問(wèn)并攜帶Cookie, const.js 為寫(xiě)死的要攜帶的cookie
let koa2Req = require('koa2-request') let constConfig = require('./const') let iToken = constConfig.iToken let koaRequest = async function(url, method, ctx) { let options = { method: method, uri: url, timeout: 120000, body: ctx ? { ...ctx.request.body } : null, headers: {}, json: true // Automatically stringifies the body to JSON } options.headers['Cookie'] = `i-token=${iToken}` //設(shè)置cookie let res = await koa2Req(options) return res.body } // node-mon async function getTestToken() { if (!constConfig.iToken) { let url = `http://xt.eqxiu.com/tui/app/radar/test/getToken?companyId=${constConfig.companyId}&staffId=${constConfig.staffId}` try { let res = await koaRequest(url, 'GET') iToken = res.obj console.log('token已拿到:' + iToken) } catch (e) { console.log(e) } } } getTestToken() module.exports = koaRequest
3.4 最后設(shè)置端口等
const app = require('./app') //const createWebsocket = require('./websocket') const server = require('http').createServer(app.callback()) server.setTimeout(2 * 60 * 1000) //設(shè)置超時(shí)時(shí)間 const { PORT = 3000 } = process.env server.listen(PORT, () => { console.log(`Listening on port ${PORT}`) })
3.5 本地開(kāi)發(fā),熱重啟
安裝 nodemon
yarn add nodemon
設(shè)置忽略監(jiān)聽(tīng)
nodemon.josn node項(xiàng)目根目錄下
{ "ignore": ["node_modules/*"] //忽略node_modules下文件修改的監(jiān)聽(tīng) }
package.josn
通過(guò)npm run server啟動(dòng)
{ "dependencies": { "koa": "^2.8.1", "koa-bodyparser": "^4.2.1", "koa-router": "^7.4.0", "koa2-request": "^1.0.4", "nodemon": "^1.19.1" }, "scripts": { "server": "nodemon index.js" } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。