Node中使用http-proxy-middleware實(shí)現(xiàn)代理跨域的方法步驟
更新時(shí)間:2021年11月15日 10:02:08 作者:lihefei_coder
本文主要介紹了Node中使用http-proxy-middleware實(shí)現(xiàn)代理跨域的方法步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
1.安裝代理模塊
cnpm i http-proxy-middleware -S
2.配置代理
const express = require('express'); const app = express(); /* 代理配置 start */ const proxy = require('http-proxy-middleware'); //引入代理模塊 const proxyOptions = { target: 'http://127.0.0.1:9999', //后端服務(wù)器地址 changeOrigin: true //處理跨域 }; const exampleProxy = proxy('/api/*', proxyOptions); //api前綴的請(qǐng)求都走代理 app.use(exampleProxy); /* 代理配置 end */ const hostName = '127.0.0.1'; const port = 8080; app.get('/', function(req, res) { const html = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <button id="btn1">請(qǐng)求服務(wù)器接口1</button> <button id="btn2">請(qǐng)求服務(wù)器接口2</button> <script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script> <script> document.getElementById('btn1').addEventListener( 'click', () => { axios.get('/api/hello', { params: { key: 'hello' } }); }, false ); document.getElementById('btn2').addEventListener( 'click', () => { axios.get('/api/word', { params: { key: 'word' } }); }, false ); </script> </body> </html>`; res.setHeader('Content-Type', 'text/html'); res.send(html); }); app.listen(port, hostName, function() { console.log(`服務(wù)器運(yùn)行在http://${hostName}:${port}`); });
到此這篇關(guān)于Node中使用http-proxy-middleware實(shí)現(xiàn)代理跨域的方法步驟的文章就介紹到這了,更多相關(guān)Node http-proxy-middleware代理跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs實(shí)現(xiàn)超簡單生成二維碼的方法
這篇文章主要介紹了nodejs實(shí)現(xiàn)超簡單生成二維碼的方法,結(jié)合實(shí)例形式分析了nodejs基于qr-image插件生成二維碼的相關(guān)操作技巧,需要的朋友可以參考下2018-03-03關(guān)于node+mysql數(shù)據(jù)庫連接池連接
這篇文章主要介紹了關(guān)于node+mysql數(shù)據(jù)庫連接池連接,mysql有兩種連接方式:一種是直接連接 另一種是池化連接,我們這篇講的是池化連接,需要的朋友可以參考下2023-04-04Nodejs高擴(kuò)展性的模板引擎 functmpl簡介
本文給大家分享的是一款nodejs高擴(kuò)展性的模板引擎functmpl的簡單介紹以及用法詳解,有需要的小伙伴可以參考下2017-02-02React和Node.js快速上傳進(jìn)度條功能實(shí)現(xiàn)
這篇文章主要為大家介紹了React和Node.js快速上傳進(jìn)度條功能實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03利用Node.js+Koa框架實(shí)現(xiàn)前后端交互的方法
這篇文章主要給大家介紹了利用Node.js+Koa框架實(shí)現(xiàn)前后端交互的方法,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-02-02