Nodejs koa2代理跨域

本文介绍如何使用Koa2框架和koa2-proxy-middleware模块实现代理功能,解决前端开发中常见的跨域问题。通过具体代码示例,展示了如何配置代理模块,使指定API前缀的请求能够通过代理服务器转发到目标服务器。

1.安装代理模块

cnpm i koa2-proxy-middleware -S

2.配置代理

const Koa = require('koa');
const app = new Koa();

/* 代理配置 start */
const proxy = require('koa2-proxy-middleware'); //引入代理模块
const proxyOptions = {
    target: 'http://127.0.0.1:9999', //后端服务器地址
    changeOrigin: true //处理跨域
};
const exampleProxy = proxy('/api/*', proxyOptions); //api前缀的请求都走代理
app.use(exampleProxy); //注册
/* 代理配置 end */


app.use(async ctx => {
    ctx.type = 'html';
    ctx.body = 
    `<!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">请求服务器接口1</button>
	        <button id="btn2">请求服务器接口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>`;
});
const hostName = '127.0.0.1'; //本地IP
const port = 8888; //端口
app.listen(port, hostName, () => {
    console.log(`服务运行在http://${hostName}:${port}`);
});
console.log('服务启动成功');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值