A服务下有个页面访问B服务的接口,会出现跨域的限制。A服务可以利用Jsonp来实现跨域,此时B服务下的接口需要配合写callback才能实现跨域功能。还有个方法,可以用nginx实现跨域。
实现的结果就是:通过访问nginx的服务时,访问的是A服务下的页面,A页面请求B接口时走nginx的服务,对于浏览器来说,一直走的是nginx的服务。所以,最终就实现了跨域的功能。
A页面代码:(访问地址是http://localhost:3001)
<body>
<div id="data"></div>
<script type="text/javascript">
$(function(){
$.get("/string",function(data){
console.log(data)
$('#data').append(data)
})
})
</script>
</body>
B是node服务,提供A页面需要的接口:(访问地址是http://localhost:3000)
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
await ctx.render('index', {
title: 'Hello Koa 2!'
})
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
module.exports = router
nginx服务配置文件:
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://localhost:3001;
proxy_redirect default;
}
location ~ /string {
proxy_pass http://localhost:3000;
}
。。。
}
浏览器通过nginx访问8080端口时,实际访问的是3001端口,3001端口访问3000端口时,通过8080端口去访问的。nginx就把A和B两个服务归拢到8080端口下。
1.安装nginx
brew install nginx
2.nginx配置文件nginx.conf所在目录
/usr/local/etc/nginx
3.启动和关闭
启动:nginx
关闭:nginx -s stop
当A服务的页面需要调用B服务接口时,遇到跨域限制。除了使用Jsonp,还可以通过配置nginx实现跨域。nginx作为代理,将A服务的3001端口和B服务的3000端口统一到8080端口下,使得浏览器通过nginx访问,从而规避跨域限制。

1345

被折叠的 条评论
为什么被折叠?



