Nodejs koa2代理跨域

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 = 
    `
	
	    
	        
	        
	        
	        Document
	    
	    
	        
	        
	        
	        
	    
	`;
});
const hostName = '127.0.0.1'; //本地IP
const port = 8888; //端口
app.listen(port, hostName, () => {
    console.log(`服务运行在http://${hostName}:${port}`);
});
console.log('服务启动成功');

你可能感兴趣的:(nodejs,koa,koa2,代理,跨域)